﻿<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!DOCTYPE html><HTML><HEAD>
<META content="chrome=1,IE=10" http-equiv="X-UA-Compatible">
<META content="text/html; charset=utf-8" http-equiv="Content-Type">
<SCRIPT type="text/javascript">
var NREUMQ=NREUMQ||[];
NREUMQ.push(["mark","firstbyte",new Date().getTime()]);
</SCRIPT>
<LINK rel="shortcut icon" href="/favicon.png">
<LINK rel="icon" type="image/png" href="/favicon.png">
<META name="viewport" content="width=1100">
<TITLE>RookieSoft CRM</TITLE>
<LINK rel="stylesheet" type="text/css" href="style/default/css/main.css">
<LINK rel="stylesheet" type="text/css" href="body.css">
<SCRIPT language="javascript" type="text/javascript" src="js/javascript.js"></SCRIPT>

<SCRIPT type="text/javascript">
      WebFontConfig = {
        google: { families: [ 'Droid Serif:400,600,700:latin','Open+Sans:400,600,700:latin' ] }
      };
      (function() {
        var wf = document.createElement('script');
        wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
            '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
        wf.type = 'text/javascript';
        wf.async = 'true';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(wf, s);
      })();
    
    </SCRIPT>

<SCRIPT type="text/javascript">
var SessionCheckTime = 120000;
var SidebarOffset;
var PermSidebarScroll = $('#PermSidebar').scrollTop();

$(function(){
	setTimeout("CheckSessionStatus();", SessionCheckTime);

	ClickOffElement('.SidebarDropdownContent', ".SidebarContent")

	$('.SidebarDropdownHeader').click(function(event){
		Element = $(this).attr('Element');
		event.stopPropagation();
		$('#SidebarContent_'+Element).slideDown('fast');
	});
	
	//Set up some common funcions
	$('.IconSprite-remove').live("mouseover", function(){
		$(this).addClass("IconSprite-remove_red");
	});
	$('.IconSprite-remove').live("mouseout", function(){
		$(this).removeClass("IconSprite-remove_red");
	});
	
	$('#HeaderSearchBarDiv').bind('mouseover', function(){
		ShowGroupSearchOptions();
	});
	
	$('#HeaderSearchBarDiv').bind('mouseout', function(){
		HideGroupSearchOptions();
	});
	
	$(window).resize(function() {
		ResizeWindow();
	});
	
	
	$('.NavItem').mouseenter(function() {
		$('#NavPopup_'+$(this).attr('NavType')).show();
	}).mouseleave(function(){
		$('#NavPopup_'+$(this).attr('NavType')).hide();
	});
	
	
	//Code for fixing the sidebar on the right side
	
	$window    = $(window),
	SidebarOffset = $('.HeaderWrapperDiv').height()+$('.NavigationBar').height()+21;
	
	//set the min-height of the pages
	$('.AJAXPageTemplate, #BodyMain').css('min-height', ($(window).height()-SidebarOffset)+'px'); 
	
	ResizeWindow();
	
});

var ResizeEvent = null;
var ResizeWindowCount = 0;
var ResizeWindow = function() {
	var delay = 50; /* milliseconds - vary as desired */
	var executionTimer;
	
	return function() {
		if (executionTimer) {
			clearTimeout(executionTimer);
		}
		
		executionTimer = setTimeout(function() {
			var SidebarWidth = 0;
			var BodyWidth = $('body').width();
			
			if($('#PermSidebar').is(':visible'))
				SidebarWidth = $('#PermSidebar').width()+1;
			$('#BodyMain').css('width', Math.min(1280+22, BodyWidth) - 22-SidebarWidth); //the 24 pixels is for the padding around the body plus some borders
			var NewWidth = $('.MainContent').width();
			$('.MainContentWrapper').css('min-height', $(window).height()+'px');
			
			UpdatePageGrayOutSize();
			
			//get the navigation bar to look right
			var TotalWidth = 0;
			$('.NavItem').css('margin-right', '0px');
			$('.NavText').show();
			$('.NavItem').each(function(){
				TotalWidth += $(this).width();
			});
			$('.NavGuideItem').each(function(){
				TotalWidth += $(this).outerWidth();
			});
			
			if(TotalWidth >= NewWidth){
				$('.NavText').hide();
			}
			else{
				//everything should fit, but we might need to add spacing
				$('.NavItem').css('margin-right', (Math.floor((NewWidth - TotalWidth)/$('.NavItem').length))+'px');
			}
			
			//resize the floating sidebar
			if(typeof IsAppDirectory !== 'undefined'){
				PermSidebarObject.ResizePermSidebar();
				HorizontalSidebarOffset = Math.max(11, (BodyWidth - 1280) / 2);
				$('#PermSidebar').css('right',HorizontalSidebarOffset+'px');
				$('.PermSidebarTitle').css('right',HorizontalSidebarOffset+'px');
			}
				
			if(ResizeEvent != null){
				setTimeout(ResizeEvent, 0);
			}
		}, delay);
	};
}();

function CheckSessionStatus(){
	$.post('/ajax/checksession.php', {}, function(data){
		if(data == 'FALSE'){
			window.location.reload();
			return false;
		}
		else if(data == 'WARNING'){
			$('#SessionTimeoutNotice').slideDown('fast');
		}
		else{
			$('#SessionTimeoutNotice').hide();
		}
	});
	
	setTimeout("CheckSessionStatus();", SessionCheckTime);
}

function RefreshSession(){
	$('#SessionTimeoutNotice').hide();
	$.post('/ajax/refreshsession.php', {}, function(data){
		if(data == 'FALSE'){
			window.location.reload();
			return false;
		}
	});
}

function InsertMarkupFromAJAX(Data){
	$('#SessionTimeoutNotice').hide();
	//Dialog(Data);
	try{
	eval("var NewData = "+Data); 

	for ( var i in NewData ){
		Module = NewData[i];
		
		
			if(Module['Type'] == 'CallJSFunction'){
				eval(Module['Function']+'(Module["Content"]'+")");
			}
			else if(Module['Type'] == 'Title'){
				document.title = Module['Content'];
			}
			else if(Module['Type'] == 'ExecuteJS'){
				eval(""+Module["Content"]);
			}
			else if(Module['Type'] == 'Debug'){
				Dialog(Module['Content']);
			}
			else{
				//Assume the type is "HTML"
				
				if(Module['InsertType'] == 'prepend'){
					$(Module['Element']).prepend(Module['Content']);
				}
				else if(Module['InsertType'] == 'append'){
					$(Module['Element']).append(Module['Content']);
				}
				else{
					$(Module['Element']).html(Module['Content']);
				}
			}
		}
	}
	catch(err){
		Dialog("<h2 style='color:#E76619;'>There was an error</h2>"+err+"<br /><hr />"+Data);
	}
	
	try{
		ProcessLinks();
	}
	catch(err){
		
	}
}

function NewPhoneCallDialog(){
	Dialog("<div class='DialogHeader'>Place a phone call</div><div style='padding:20px;' id='PhoneCallDiv'><input type='text' id='NewPhoneCallNumber' class='BoldFormField'/>\
		<br />"+$('#OutgoingPhoneSource').html()+"<br /><a href='javascript://' onclick='StartPhoneCall();' class='GreenButton'>Place call</div>");
	//$('#NewPhoneCallNumber').val();
	$('#NewPhoneCallNumber').focus();
}

function StartPhoneCall(){
	var Number = $('#NewPhoneCallNumber').val();
	
	if(Number == ''){
		alert('please enter a phone number');
		return;
	}
	
	var OutgoingPhoneNumber = $('#PhoneCallDiv').find('#OutgoingPhoneNumbers').val();
	
	GrayOutArea('#PhoneCallDiv', true);
	$.post('/ajax/app/phone/start_call.php', {PhoneNumber:Number, OutboundNumber:OutgoingPhoneNumber}, function(Data){
		if(Data){
			$('#PhoneCallDiv').html("ERROR: "+Data);
		}
		else{
			$('#PhoneCallDiv').html("Placing call now. Your phone should ring momentarily.");
		}
	});
	
}

</SCRIPT>

<STYLE>
.AJAXPageTemplate{
	display:none;
}
</STYLE>

<META name="GENERATOR" content="MSHTML 9.00.8112.16443"></HEAD>
<BODY>
<DIV style='color: white; line-height: 33px; font-size: 15px; font-weight: bold; display: none; min-height: 35px; background-image: url("/i/app/warning_back.png"); background-repeat: repeat-x; background-color: rgb(170, 0, 0);' 
id="SessionTimeoutNotice" align="center">				You will be logged out soon due to 
inactivity. 				<A style="color: white;" onclick="RefreshSession();" href="javascript://">Click 
here to refresh your session so that you won't be logged out</A></DIV>
<DIV class="HeaderWrapperDiv" align="center">
<DIV class="HeaderDiv" align="left">
<TABLE style="height: 44px;" cellSpacing="0" cellPadding="0" width="100%">
  <TBODY>
  <TR>
    <TD class="Logo" vAlign="top" noWrap="">
      <DIV style="float: left;"><A id="HeaderLinkValue" href="https://www.lessannoyingcrm.com/app/Workspace">RookieSoft 
      CRM</A></DIV></TD>
    <TD vAlign="top" noWrap="">
      <DIV style="line-height: 13px; margin-left: 30px;">
      <DIV style="color: rgb(153, 153, 153); font-size: 10px;">Powered by</DIV>
      <DIV style="color: rgb(102, 102, 102); font-size: 13px; font-weight: bold; text-shadow: #fff 1px 1px 1px;" 
      class="Serif">Less Annoying CRM</DIV></DIV></TD>
    <TD vAlign="top" width="50%" noWrap="">
      <DIV style="color: rgb(102, 102, 102); padding-left: 30px; font-size: 11px; font-weight: normal;" 
      class="SansSerif"><SPAN id="CurrentUserName">Kyle Zhang</SPAN>							|
      							<A style="color: rgb(102, 102, 102);" href="https://www.lessannoyingcrm.com/account/logout.php">Log 
      out</A></DIV></TD>
    <TD vAlign="top" width="50%" noWrap="" align="right"><A style='background-image: url("style/default/images/main/user.png");' 
      class="HeaderIconLink" href="https://www.lessannoyingcrm.com/app/Add_Contact" 
      ReplaceClick='AddContactObject.NewForm("Contact");'>Add a new 
      contact</A><A style='background-image: url("style/default/images/main/company.png");' 
      class="HeaderIconLink" href="https://www.lessannoyingcrm.com/app/Add_Contact?IsCompany=1" 
      ReplaceClick='AddContactObject.NewForm("Company");'>Add a new 
    company</A></TD></TR></TBODY></TABLE></DIV></DIV>
<DIV class="MainContentWrapper" align="center">
<DIV class="MainContent" align="left">
<DIV class="NavigationBar">
<DIV style="width: 5000px;">
<DIV style="border-top-left-radius: 10px; text-shadow: 1px 1px 1px #000;" class="NavGuideItem"><A 
style="text-decoration: none;" href="https://www.lessannoyingcrm.com/app/Guide">
<DIV style="padding: 0px 10px; height: 46px; color: white; line-height: 12px;" 
align="center">
<DIV style="font-size: 16px; font-weight: bold; margin-top: 8px;" class="NavGuideText">Beginner's 
Guide</DIV>
<DIV style="margin-top: 6px;" id="NavGuidePercentComplete" 
class="NavGuideText">8% complete</DIV></DIV></A></DIV>
<DIV style="border-top-left-radius: 10px;" class="NavItem" 
NavType="Workspace"><A class="NavLink" href="https://www.lessannoyingcrm.com/app/Workspace"><IMG 
style="top: 6px; position: relative;" src="style/default/images/main/dashboard.png" 
width="27" height="25"><SPAN class="NavText">Your Workspace</SPAN></A>
<DIV id="NavPopup_Workspace" class="NavPopup"><A class="NavRowLink" href="https://www.lessannoyingcrm.com/app/Workspace">
<DIV class="NavRow">
<DIV class="NavRowTitle"><IMG class="Icon" src="favicon.png"> 
Your Workspace					</DIV>
<DIV class="NavRowDescription">						Your agenda, tasks, pipeline summaries, and 
activity feed, all in one place.					</DIV></DIV></A><A class="NavRowLink" href="https://www.lessannoyingcrm.com/app/Recent_Activity">
<DIV class="NavRow">
<DIV class="NavRowTitle"><SPAN class="IconSprite IconSprite-book_open"></SPAN> 
Activity Report					</DIV>
<DIV class="NavRowDescription">						A detailed report of all activity in the 
CRM with filters for date and activity type.					</DIV></DIV></A><!--
				<a href='/app/Workspace_Settings' class='NavRowLink'><div class='NavRow'>
					<div class='NavRowTitle'>
						<span class='IconSprite IconSprite-cog' ></span> Workspace Settings
					</div>
					<div class='NavRowDescription'>
						Customize your overview reports, and the type of activity you'd like to see.
					</div>
				</div></a>
				--></DIV></DIV>
<DIV class="NavItem" NavType="Contacts"><A class="NavLink" href="https://www.lessannoyingcrm.com/app/Browse"><IMG 
style="top: 5px; position: relative;" src="style/default/images/main/address_book.png" 
width="22" height="22"><SPAN class="NavText">Find a Contact</SPAN></A>
<DIV id="NavPopup_Contacts" class="NavPopup"><A class="NavRowLink" href="https://www.lessannoyingcrm.com/app/Browse">
<DIV class="NavRow">
<DIV class="NavRowTitle"><SPAN class="IconSprite IconSprite-group"></SPAN>  View 
all contacts and companies					</DIV></DIV></A>
<DIV style="padding: 20px 10px 10px;">
<DIV style="border: 1px solid rgb(153, 153, 153); width: 330px; height: 30px; overflow: hidden; margin-right: 1px; position: relative; background-color: rgb(255, 255, 255);">
<FORM id="SidebarSearchForm" method="get" action="/app/Browse"><INPUT style="margin: 0px; padding: 7px; border: 0px solid rgb(255, 255, 255); left: 0px; top: 0px; width: 290px; font-size: 14px; position: absolute; background-color: rgb(255, 255, 255);" 
id="SidebarSearch" name="Search" type="text"><INPUT style="top: 3px; width: 24px; height: 24px; right: 3px; position: absolute;" 
alt="Search Contacts" src="style/default/images/main/search.png" 
type="image"><INPUT name="SortField" value="Relevance" type="hidden"><INPUT 
name="SortDirection" value="DESC" type="hidden"></FORM></DIV><BR><BR>
<DIV style="text-align: left; line-height: 18px; overflow: hidden; white-space: normal; min-height: 40px;">
<DIV id="SidebarGroupsDiv">
<DIV style="color: rgb(102, 102, 102); margin-bottom: 10px;" class="BoldGray" 
align="center">				Did you know that you can create groups to keep your contacts 
organized?			</DIV>
<DIV class="BoldGray" align="center"><A style="color: rgb(61, 106, 166);" href="https://www.lessannoyingcrm.com/app/Groups">Click 
here to learn more about groups</A></DIV></DIV></DIV></DIV></DIV></DIV>
<DIV class="NavItem" NavType="Pipelines"><A class="NavLink" href="https://www.lessannoyingcrm.com/app/List_Pipelines"><IMG 
style="top: 3px; position: relative;" src="style/default/images/main/pipeline.png" 
width="20" height="18"><SPAN class="NavText">Pipelines</SPAN></A>
<DIV id="NavPopup_Pipelines" class="NavPopup">
<TABLE cellSpacing="0" cellPadding="0" width="100%">
  <TBODY>
  <TR>
    <TD width="99%"><A class="NavRowLink" href="https://www.lessannoyingcrm.com/app/Reports/Active?PipelineId=47557">
      <DIV class="NavRow">
      <DIV style="color: rgb(61, 106, 166);" class="NavRowTitle"><SPAN class="IconSprite IconSprite-money"></SPAN> 
      Leads						</DIV></DIV></A></TD>
    <TD style="border-left-color: rgb(204, 204, 204); border-left-width: 1px; border-left-style: solid;" 
    noWrap=""><A class="NavRowLink" href="https://www.lessannoyingcrm.com/app/Add_Contact?PipelineId=47557" 
      ReplaceClick='AddContactObject.NewForm("","",47557);'>
      <DIV style="padding-right: 0px; padding-left: 3px;" class="NavRow">
      <DIV style="width: 50px; color: rgb(61, 106, 166); padding-right: 0px; font-size: 12px; font-weight: normal;" 
      class="NavRowTitle"><SPAN class="IconSprite IconSprite-add"></SPAN> New
      						</DIV></DIV></A></TD></TR>
  <TR>
    <TD width="99%"><A class="NavRowLink" href="https://www.lessannoyingcrm.com/app/Reports/Active?PipelineId=47560">
      <DIV class="NavRow">
      <DIV style="color: rgb(61, 106, 166);" class="NavRowTitle"><SPAN class="IconSprite IconSprite-briefcase"></SPAN> 
      bills						</DIV></DIV></A></TD>
    <TD style="border-left-color: rgb(204, 204, 204); border-left-width: 1px; border-left-style: solid;" 
    noWrap=""><A class="NavRowLink" href="https://www.lessannoyingcrm.com/app/Add_Contact?PipelineId=47560" 
      ReplaceClick='AddContactObject.NewForm("","",47560);'>
      <DIV style="padding-right: 0px; padding-left: 3px;" class="NavRow">
      <DIV style="width: 50px; color: rgb(61, 106, 166); padding-right: 0px; font-size: 12px; font-weight: normal;" 
      class="NavRowTitle"><SPAN class="IconSprite IconSprite-add"></SPAN> New
      						</DIV></DIV></A></TD></TR></TBODY></TABLE>
<DIV style="padding: 10px;" align="center"><A href="https://www.lessannoyingcrm.com/account/pipelines">Customize 
pipeline settings</A></DIV></DIV></DIV>
<DIV class="NavItem" NavType="Calendar"><A class="NavLink" href="https://www.lessannoyingcrm.com/app/Calendar/View"><IMG 
style="top: 5px; position: relative;" src="style/default/images/main/calendar.png" 
width="22" height="22"><SPAN class="NavText">Calendar</SPAN></A>
<DIV id="NavPopup_Calendar" class="NavPopup"><A class="NavRowLink" href="https://www.lessannoyingcrm.com/app/Calendar/View">
<DIV class="NavRow">
<DIV class="NavRowTitle"><SPAN class="IconSprite IconSprite-calendar"></SPAN> 
View your Calendar					</DIV></DIV></A><A class="NavRowLink" onclick="EventObject.NewEventDialog();" 
href="javascript://">
<DIV class="NavRow">
<DIV class="NavRowTitle"><SPAN class="IconSprite IconSprite-date_add"></SPAN>  
Add a new event					</DIV></DIV></A><A class="NavRowLink" onclick="ReminderObject.NewReminder();" 
href="javascript://">
<DIV class="NavRow">
<DIV class="NavRowTitle"><SPAN 
class="IconSprite IconSprite-checkbox_tick"></SPAN>  Add a new task
					</DIV></DIV></A>
<DIV>
<DIV style="padding: 10px; overflow: hidden; font-size: 11px; overflow-y: auto; max-height: 400px;" 
id="ReminderSidebarDiv">
<DIV style="line-height: 16px; margin-bottom: 20px;">
<DIV style="color: rgb(153, 153, 153); font-size: 115%;" class="SidebarReminderDay">
			Today's Events		</DIV>
<DIV style="font-size: 90%;" align="center">You don't have any events scheduled 
today.</DIV></DIV>
<DIV style="line-height: 14px; margin-bottom: 15px;">
<DIV style="color: rgb(153, 153, 153); font-size: 115%;" class="SidebarReminderDay">
			Today's tasks		</DIV>
<DIV style="font-size: 90%;" align="center">You don't have anything due 
today.</DIV></DIV></DIV></DIV></DIV></DIV>
<DIV class="NavItem" NavType="Settings"><A class="NavLink" href="https://www.lessannoyingcrm.com/account/settings"><IMG 
style="top: 5px; position: relative;" src="style/default/images/main/settings.png" 
width="22" height="22"><SPAN class="NavText">Settings</SPAN></A>
<DIV style="right: -50px;" id="NavPopup_Settings" class="NavPopup"><A class="NavRowLink" 
href="https://www.lessannoyingcrm.com/account/settings">
<DIV class="NavRow">
<DIV class="NavRowTitle"><SPAN class="IconSprite IconSprite-cog"></SPAN> View 
all settings options					</DIV>
<DIV class="NavRowDescription">						Less Annoying CRM can be customized to do 
just about anything. Click here						to see the full list of options
					</DIV></DIV></A>
<TABLE cellSpacing="0" cellPadding="0" width="100%">
  <TBODY>
  <TR>
    <TD width="50%"><A class="NavRowLink" href="https://www.lessannoyingcrm.com/account/import">
      <DIV class="NavRow">
      <DIV class="NavRowTitle"><SPAN 
      class="IconSprite IconSprite-computer_go"></SPAN> Import contacts
      						</DIV></DIV></A></TD>
    <TD style="border-left-color: rgb(204, 204, 204); border-left-width: 1px; border-left-style: solid;"><A 
      class="NavRowLink" href="https://www.lessannoyingcrm.com/account/export">
      <DIV class="NavRow">
      <DIV class="NavRowTitle"><SPAN 
      class="IconSprite IconSprite-page_excel"></SPAN> Export contacts
      							</DIV></DIV></A></TD></TR></TBODY></TABLE>
<DIV style="padding: 5px 10px; font-size: 11px; font-weight: bold;" class="InvertColors">
					Quick Links				</DIV><A class="NavRowLink" href="https://www.lessannoyingcrm.com/account/settings/users.php">
<DIV class="NavRow">
<DIV class="NavRowTitle"><SPAN class="IconSprite IconSprite-user_add"></SPAN> 
Add users to your account					</DIV></DIV></A><A class="NavRowLink" href="https://www.lessannoyingcrm.com/account/pipelines">
<DIV class="NavRow">
<DIV class="NavRowTitle"><SPAN class="IconSprite IconSprite-chart_bar"></SPAN> 
Customize your pipelines					</DIV></DIV></A><A class="NavRowLink" href="https://www.lessannoyingcrm.com/account/settings/email.php">
<DIV class="NavRow">
<DIV class="NavRowTitle"><SPAN class="IconSprite IconSprite-email"></SPAN> Set 
up email logging					</DIV></DIV></A><A class="NavRowLink" href="https://www.lessannoyingcrm.com/account/settings/google.php">
<DIV class="NavRow">
<DIV class="NavRowTitle"><IMG class="Icon" src="style/default/images/main/google.png"> 
Sync with Google					</DIV></DIV></A><A class="NavRowLink" href="https://www.lessannoyingcrm.com/account/mailchimp">
<DIV class="NavRow">
<DIV class="NavRowTitle"><IMG class="Icon" src="style/default/images/main/mailchimp.png"> 
Set up email marketing integration					</DIV></DIV></A><A class="NavRowLink" 
href="https://www.lessannoyingcrm.com/account/settings">
<DIV class="NavRow" align="center">
<DIV class="NavRowTitle">						View more settings options					</DIV></DIV></A><A 
style="text-decoration: none;" href="https://www.lessannoyingcrm.com/account/invite/">
<DIV class="NavReferralRow">
<DIV style="padding: 20px 10px 10px; font-size: 22px; font-weight: bold;" align="center">
							We love referrals!						</DIV>
<DIV style="padding: 10px; font-size: 13px;">							Click here to learn how you 
can give your friends							an extra-long free trial, and help us spread the 
word.						</DIV></DIV></A></DIV></DIV>
<DIV class="NavItem" NavType="Help"><A class="NavLink" href="https://www.lessannoyingcrm.com/contact.php"><IMG 
style="top: 4px; position: relative;" src="style/default/images/main/help.png" 
width="24" height="20"><SPAN class="NavText">Help</SPAN></A>
<DIV style="right: 0px;" id="NavPopup_Help" class="NavPopup"><A class="NavRowLink" 
href="https://www.lessannoyingcrm.com/contact.php">
<DIV class="NavRow">
<DIV class="NavRowTitle"><SPAN class="IconSprite IconSprite-comment"></SPAN> 
Contact Us					</DIV>
<DIV class="NavRowDescription">						Have a question? We're here to help! Email 
and phone support are always 100% free.					</DIV></DIV></A><A class="NavRowLink" 
href="https://www.lessannoyingcrm.com/app/Guide">
<DIV class="NavRow">
<DIV class="NavRowTitle"><SPAN class="IconSprite IconSprite-film"></SPAN> 
Beginner's Guide					</DIV>
<DIV class="NavRowDescription">						A series of short videos showing you 
everything you need to know about Less Annoying CRM.					</DIV></DIV></A><A 
class="NavRowLink" href="https://www.lessannoyingcrm.com/help">
<DIV class="NavRow">
<DIV class="NavRowTitle"><SPAN class="IconSprite IconSprite-book"></SPAN> Help 
Documentation					</DIV>
<DIV class="NavRowDescription">						Find the answers to all of your questions 
here.					</DIV></DIV></A>
<DIV style="padding-bottom: 15px;" align="center">
<DIV style="color: rgb(102, 102, 102); padding-top: 15px; padding-bottom: 7px; font-size: 12px;">Follow 
us for tips and product updates:</DIV>
<TABLE cellSpacing="0" cellPadding="0">
  <TBODY>
  <TR>
    <TD style="padding-right: 8px;"><A href="http://www.facebook.com/LessAnnoyingCRM" 
      target="_blank"><IMG src="style/default/images/main/facebook.png" 
      width="48" height="48"></A></TD>
    <TD style="padding-right: 8px;"><A href="https://plus.google.com/117969278028568849880/posts" 
      target="_blank"><IMG src="style/default/images/main/google(1).png" 
      width="48" height="48"></A></TD>
    <TD style="padding-right: 8px;"><A href="http://www.linkedin.com/company/less-annoying-crm" 
      target="_blank"><IMG src="style/default/images/main/linkedin.png" 
      width="48" height="48"></A></TD>
    <TD><A href="https://twitter.com/#!/LessAnnoyingCRM" target="_blank"><IMG 
      src="style/default/images/main/twitter.png" width="48" 
      height="48"></A></TD></TR></TBODY></TABLE></DIV></DIV></DIV></DIV></DIV>
<DIV style="overflow: hidden;">
<DIV id="PermSidebar"></DIV>
<DIV style="overflow: hidden; border-right-color: rgb(153, 153, 153); border-right-width: 1px; border-right-style: solid; position: relative; z-index: 1; min-height: 1200px; box-shadow: 0px 0px 15px #000; background-color: rgb(255, 255, 255);" 
id="BodyMain">
<SCRIPT type="text/javascript">

var CurrentPage = "/app/Workspace";
var OriginalCurrentPage = "/app/Workspace";
var IsAppDirectory = true;

var PageSettings = new Array();
var TempPageSettings = new Array();

var DontScroll = false;

var CurrentPageParams = {};

jQuery(document).ready(function($){
	$.history.init(function(hash){
		var HashPage = window.location.hash.replace("#", "");
		if(hash == "" ||  HashPage == "") {
			LoadPage(OriginalCurrentPage, DontScroll);
		} else {
			LoadPage(HashPage, DontScroll);
		}
		DontScroll = false;
	},
	{ unescape: ",/?=&" });
	
	ReplaceJavascriptLinks();
});

$(function(){		
	ProcessLinks();
	
	//preload images
	LoadingGif = new Image(); 
	LoadingGif.src = "style/default/images/main/loading.gif";	
});

function LoadPage(Type, DontScroll){
	ResizeEvent = null;
	ResizeWindow();
	
	$('#SessionTimeoutNotice').hide();
	$('.NavPopup').slideUp('fast');
	OldCurrentPage = CurrentPage;
	CurrentPage = Type;
	
	if(CurrentPage.toLowerCase() != '/app/calendar/view' && OldCurrentPage.toLowerCase() == '/app/calendar/view'){
		CalendarObject.ClearDisplay();
	}
	
	if(DontScroll == null)
		DontScroll = false;
	
	if(!DontScroll){
		$('body').scrollTop(0);
		$("html").scrollTop(0);
	}
	
	SetBodyColumn(-1);
	
	Type = Type.split("?");
	var Params = Type[1];
	Type = Type[0];
	Type = Type.toLowerCase();
	Type = Type.replace("/app/", "");
	
	//break the parameters into an array so it can be accessed via javascript
	CurrentPageParams = {};
	
	if(Params != null){
		var ParamArray = Params.split('&');
		for(i = 0; i < ParamArray.length; i++){
			Vals = ParamArray[i].split('=');
			
			if(Vals[0] != null && Vals[1] != null && Vals[0] != '' && Vals[1] != ''){
				//no idea why this needs two urldecodes, but I'm not going to argue with the computer gods
				CurrentPageParams[Vals[0]] = urldecode(urldecode(Vals[1]));	
			}
		}
	}
	
	if(Type == ''){
		Type = 'workspace';
	}
	
	EscapedPage = Type.replace(/\//g, "__");
	
	$('.AJAXPageTemplate').hide();
	if(	$('#AJAXPAGE_'+EscapedPage).length > 0){
		
		$('#AJAXPAGE_'+EscapedPage).show();
		if(PageSettings[EscapedPage] != null){
		
			document.title = PageSettings[EscapedPage]['PageTitle'];
		
			if(PageSettings[EscapedPage]['GetAJAXContent']){
				LoadingPageGraphic();
				$.post('/appinclude/data/'+Type+'.php?'+Params, {}, function(data){
					InsertMarkupFromAJAX(data)
					CloseLoadingPageGraphic();
				});
			}
			
			if(PageSettings[EscapedPage]['JSBeforeAJAX'] != ''){
				eval(""+PageSettings[EscapedPage]['JSBeforeAJAX']);
			}
		}
		
	}
	else{
		$('#AJAXPAGE_NOTFOUND').show();
		document.title = "Page not found - Less Annoying CRM";
	}
}



function InterceptClick(Element, e){
	//use the hash tag to change the page
	var HREF = $(Element).attr('href');
	HREF = HREF.replace("https://www.lessannoyingcrm.com", "")
	//alert(HREF +" - "+window.location.hash);
	
	//Find out if we should automatically scroll to the top
	if($(Element).attr('DontScroll') == 'true')
		DontScroll = true;
	else
		DontScroll = false;
	
	if(HREF == window.location.hash.replace("#", "")){
		//reload the current page
		LoadPage(CurrentPage, DontScroll);
	}
	else{
		jQuery.history.load(HREF);
	}
	
	//window.location.hash = HREF;
	//LoadPage(HREF);
}

function LoadingPageGraphic(){
	$('.LoadingPageGraphic').remove();
	$('#BodyMain').append("<div class='LoadingPageGraphic'><br /><br /><br /><img src='style/default/images/main/loading.gif' /></div>");
	$('.LoadingPageGraphic').height($('#BodyMain').height());
	$('.LoadingPageGraphic').width($('#BodyMain').width());
}

function CloseLoadingPageGraphic(){
	$('.LoadingPageGraphic').remove();
}

function ProcessLinks(Container){
	if(Container == null)
		Container = 'body';
	
	$(Container).find('a').each(function(){
		ProcessSpecificLink(this);
	});
	/*
	$(Container).find('form').each(function(){
        if($(this).attr('action').toLowerCase().startsWith("/appinclude/action/")){
			$(this).ajaxForm({success:function(Data) {
					CloseLoadingPageGraphic();
					EndGrayOutArea();
					InsertMarkupFromAJAX(Data)
				},
				beforeSubmit:function(){
					LoadingPageGraphic();
				}
			}); 
		}   
	});
	*/
}

function ProcessSpecificLink(Element){
	$(Element).each(function(){
		if($(this).attr('href') == null)
			return;
		
		var HREF = $(this).attr('href').toLowerCase();
		if($(this).attr('onmousedown') == null && HREF != "javascript://"){
			//This link hasn't been processed yet.
			
			var ShouldBeProcessed = false;
			//Figure out if it's a link/click that should be processed. Don't process mailtos, 			
			if($(this).hasClass('DontProcessLink')){
				ShouldBeProcessed = false
			}
			else if($(this).attr('href').startsWith("/app/") || 
						$(this).attr('href').startsWith("https://www.lessannoyingcrm.com/app/")){
				ShouldBeProcessed = !HREF.startsWith("mailto:");
			}
			else{
				ShouldBeProcessed = false;
			}
			
			$(this).unbind('mousedown');
			$(this).unbind('click');
			$(this).bind('mousedown', function(e){
				if(ShouldBeProcessed && e.which != 2 && e.which != 3){
					return InterceptClick(this, e);
					
				}
			});
			$(this).bind('click', function(e){
				if(ShouldBeProcessed == false){
					//alert("FALSE (for some reason) - "+$(this).attr('href').startsWith("/app/")+" - "+$(this).attr('href'));
				}
					
				if(ShouldBeProcessed && e.which != 2 && e.which != 3){
					e.preventDefault();
				}
				else{
					//alert(ShouldBeProcessed +" - "+ (e.which != 2));
					//don't do anything, let the click happen
				}
			});
		}
	});
	
	
}

function ReplaceJavascriptLinks(){
	$('[ReplaceClick]').each(function(){
		$(this).bind('click', function(){
			eval($(this).attr('ReplaceClick'));
		});
		
		$(this).attr('href', 'javascript://');
	});
}
</SCRIPT>

<DIV id="AJAXPAGE_recent_activity" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Recent Activity - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = 'PermSidebarObject.HidePermSidebar();LogAnalyticsModule("Reporting");';
	
	PageSettings["recent_activity"] = TempPageSettings;
	
	</SCRIPT>

<STYLE>
.RecentActivityContactName{
	
}
</STYLE>

<SCRIPT type="text/javascript">

$(function(){
	$('#RecentActivityStartDatePicker').datepicker({
		inline: true,
		numberOfMonths:1,
		onSelect:function(datetext, inst){
			RecentActivityObject.TempStartDate = datetext;
		}
	});
	
	$('#RecentActivityEndDatePicker').datepicker({
		inline: true,
		numberOfMonths:1,
		onSelect:function(datetext, inst){
			RecentActivityObject.TempEndDate = datetext;
		}
	});
});

var RecentActivityObject = new RecentActivityClass();	
function RecentActivityClass(){
	this.StartDate = '';
	this.EndDate = '';
	this.PipelineFilter = '';
	this.OwnerFilter = '';
	
	this.TempStartDate = '';
	this.TempEndDate = '';
	
	this.Init = function(StartDate, EndDate){
		this.StartDate = StartDate;
		this.EndDate = EndDate;
		this.TempStartDate = StartDate;
		this.TempEndDate = EndDate;
		
		$('#RecentActivityStartDatePicker').datepicker('setDate', new Date(StartDate));
		$('#RecentActivityEndDatePicker').datepicker('setDate', new Date(EndDate));
		
		//this.DateDialog();
	}
	
	this.BuildNewURL = function(){
		//We include the date to simulate a random number. This makes it so the URL will change so
		//the page will refresh even if the parameters haven't changed
		var d = new Date();
		HREF = "/app/Recent_Activity?t="+d.getTime();
		
		if(this.StartDate != '')
			HREF += "&StartDate="+this.StartDate;
		if(this.EndDate != '')
			HREF += "&EndDate="+this.EndDate;
		if(this.OwnerFilter != '')
			HREF += "&OwnerFilter="+this.OwnerFilter;
		if(this.PipelineFilter != '')
			HREF += "&PipelineFilter="+this.PipelineFilter;
		
		//Navigate to the new URL
		if(HREF == window.location.hash.replace("#", "")){
			//reload the current page
			LoadPage(HREF);
		}
		else{
			jQuery.history.load(HREF);
		}
	}
	
	this.AddMonth = function(StartDate, EndDate){
		this.StartDate = StartDate;
		this.EndDate = EndDate;
		DontScroll = true;
		this.BuildNewURL();
	}
	
	this.DateDialog = function(){
		DialogId = Dialog("<div id='RecentActivityDialogDiv'></div>", 500, "RecentActivityObject.CloseDateDialog();");
		$('#RecentActivityDateDialogSource').appendTo("#RecentActivityDialogDiv");
		RepositionDialog(DialogId, 500);
	}
	
	this.CloseDateDialog = function(){
		$('#RecentActivityDateDialogSource').appendTo("#RecentActivityDateDialogWrapper");
		CloseDialog('#RecentActivityDialogDiv');
	}
	
	this.ApplyDateRange = function(){
		this.StartDate = this.TempStartDate;
		this.EndDate = this.TempEndDate;
		this.BuildNewURL();
		this.CloseDateDialog();
	}
	
	this.FilterOwnerDialog = function(){
		DialogId = Dialog("<div id='RecentActivityDialogDiv'></div>", 500, "RecentActivityObject.CloseFilterOwnerDialog();");
		$('#RecentActivityOwnerFilterDialogDiv').appendTo("#RecentActivityDialogDiv");
		RepositionDialog(DialogId, 500);
	}
	
	this.CloseFilterOwnerDialog = function(){
		$('#RecentActivityOwnerFilterDialogDiv').appendTo("#RecentActivityOwnerFilterDialogWrapper");
		CloseDialog('#RecentActivityDialogDiv');
	}
	
	this.SetOwnerFilter = function(){
		this.OwnerFilter = $("input[name='FilterOwnerRecentActivity']:checked").val();
		this.BuildNewURL();
		this.CloseFilterOwnerDialog();
	}
	
	this.FilterPipelineDialog = function(){
		DialogId = Dialog("<div id='RecentActivityDialogDiv'></div>", 500, "RecentActivityObject.CloseFilterPipelineDialog();");
		$('#RecentActivityPipelineFilterDialogDiv').appendTo("#RecentActivityDialogDiv");
		RepositionDialog(DialogId, 500);
	}
	
	this.CloseFilterPipelineDialog = function(){
		$('#RecentActivityPipelineFilterDialogDiv').appendTo("#RecentActivityPipelineFilterDialogWrapper");
		CloseDialog('#RecentActivityDialogDiv');
	}
	
	this.SetPipelineFilter = function(){
		this.PipelineFilter = $("input[name='FilterPipelineRecentActivity']:checked").val();
		this.BuildNewURL();
		this.CloseFilterPipelineDialog();
	}
}
</SCRIPT>

<DIV id="FrameworkRecentActivity"></DIV>
<DIV style="display: none;" id="RecentActivityDateDialogWrapper">
<DIV id="RecentActivityDateDialogSource">
<DIV align="center">
<DIV class="DialogHeader">				Change the Date Range			</DIV>
<TABLE>
  <TBODY>
  <TR>
    <TD style="padding-right: 15px;" vAlign="top" align="center">
      <DIV style="color: rgb(153, 153, 153); font-size: 25px; font-weight: bold; margin-bottom: 7px;">
      						Start Date					</DIV>
      <DIV style="font-size: 11px;" id="RecentActivityStartDatePicker"></DIV></TD>
    <TD style="padding-left: 15px;" vAlign="top" align="center">
      <DIV style="color: rgb(153, 153, 153); font-size: 25px; font-weight: bold; margin-bottom: 7px;">
      						End Date					</DIV>
      <DIV style="font-size: 11px;" 
  id="RecentActivityEndDatePicker"></DIV></TD></TR></TBODY></TABLE>
<DIV style="margin-top: 25px;"><A class="GreenButton" onclick="RecentActivityObject.ApplyDateRange();" 
href="javascript://">View this date range</A></DIV><BR></DIV></DIV></DIV></DIV>
<DIV id="AJAXPAGE_calendar__view" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Calendar - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = false;
	TempPageSettings['JSBeforeAJAX'] = 'PermSidebarObject.HidePermSidebar();CalendarObject.Init();LogAnalyticsModule("Calendar");';
	
	PageSettings["calendar__view"] = TempPageSettings;
	
	</SCRIPT>

<TABLE cellSpacing="0" cellPadding="0" width="100%">
  <TBODY>
  <TR>
    <TD style="border-right-color: rgb(204, 204, 204); border-right-width: 2px; border-right-style: solid; background-color: rgb(245, 245, 245);" 
    vAlign="top" width="230">
      <DIV style="width: 230px; overflow: hidden;">
      <DIV style="display: none;" id="SidebarBoxWrapper_Calendar">
      <DIV id="SidebarHeader_Calendar" class="CalendarSidebarHeader">
      <TABLE cellSpacing="0" cellPadding="0" width="100%">
        <TBODY>
        <TR>
          <TD id="CalendarSidebarViewSelect_Day" class="CalendarSidebarViewSelect" 
          onclick='CalendarObject.SwitchViews("Day");'>							Day						</TD>
          <TD id="CalendarSidebarViewSelect_Week" class="CalendarSidebarViewSelect" 
          onclick='CalendarObject.SwitchViews("Week");'>							Week						</TD>
          <TD id="CalendarSidebarViewSelect_Month" class="CalendarSidebarViewSelect" 
          onclick='CalendarObject.SwitchViews("Month");'>							Month						</TD>
          <TD id="CalendarSidebarViewSelect_Agenda" class="CalendarSidebarViewSelect" 
          onclick='CalendarObject.SwitchViews("Agenda");'>							Agenda
          						</TD>
        <TR></TR></TBODY></TABLE></DIV>
      <DIV style="padding: 0px;" id="SidebarContent_Calendar" class="SidebarContent">
      <DIV style="padding-top: 6px; margin-bottom: 10px;" 
      id="SidebarCalendar"></DIV>
      <DIV style="padding: 5px; border-top-color: rgb(221, 221, 221); border-bottom-color: rgb(221, 221, 221); border-top-width: 1px; border-bottom-width: 1px; border-top-style: solid; border-bottom-style: solid;" 
      class="SidebarLine"><A style="top: -1px; position: relative;" class="IconSprite IconSprite-date_add" 
      onclick="EventObject.NewEventDialog();" href="javascript://">Create new 
      event</A><A style="padding-left: 4px;" onclick="EventObject.NewEventDialog();" 
      href="javascript://">Create new event</A><BR><A style="top: -1px; position: relative;" 
      class="IconSprite IconSprite-checkbox_tick" onclick="ReminderObject.NewReminder();" 
      href="javascript://">Create new task</A><A style="padding-left: 4px;" 
      onclick="ReminderObject.NewReminder();" href="javascript://">Create new 
      task</A><BR><A style="top: -1px; position: relative;" class="IconSprite IconSprite-printer" 
      onclick="CalendarObject.Display.Print();" href="javascript://">Print 
      Calendar</A><A style="padding-left: 4px;" onclick="CalendarObject.Display.Print();" 
      href="javascript://">Print Calendar</A></DIV>
      <DIV style="padding: 5px; border-bottom-color: rgb(221, 221, 221); border-bottom-width: 1px; border-bottom-style: solid;" 
      class="SidebarLine"><INPUT id="CalendarViewTasks" CHECKED="checked" type="checkbox"><LABEL 
      for="CalendarViewTasks">Show tasks on the 
      calendar</LABEL></DIV></DIV></DIV></DIV></TD>
    <TD vAlign="top">
      <DIV id="CalendarWrapper"></DIV></TD></TR></TBODY></TABLE>
<SCRIPT type="text/javascript">

$(function(){
	$('.SidebarCal_Checkbox').bind('click', function(){
		CalendarObject.ProcessCheckedCalendars();
		CalendarObject.GetEvents();
	})
	
	CalendarObject.ProcessCheckedCalendars();
	
	$('#CalendarViewTasks').change(function(){
		CalendarObject.SetTaskVisibility(true)
		CalendarObject.Display.ProcessDays();
	});
	
});


var CalendarObject = new CalendarClass();	

//This code uses the DateJS library from http://www.datejs.com/2007/11/27/getting-started-with-datejs/

function CalendarClass(){
	this.StartDate = Date.today().toString("MM/dd/yyyy");
	this.EndDate;
	this.Events = new Array();
	this.Display;
	this.DisplayedUsers
	this.View = 'Agenda';
	this.UsesInternationalTimeFormat = '0';
	this.SidebarCalBaseDate;
	this.TimezoneConfirmed;
	
	this.Init = function(){
		//$('#BodyMain').hide();
		ResizeEvent = "CalendarObject.Display.AdjustWidth()";
		
		
	
		
		this.StartDate = Date.today().toString("MM/dd/yyyy");
		
		$('#SidebarBoxWrapper_Calendar').slideDown('fast');
		
		//If the wrapper div hasn't been created yet, create it
		if($('#CalendarWrapper').length == 0){
			$('#BodyMain').append("<div id='CalendarWrapper'></div>");
		}
		else{
			$('#CalendarWrapper').show();
		}
		
		//TODO generate the list of displayed users
		this.DisplayedUsers = new Array();
		this.DisplayedUsers[0] = 4;	
		
		this.SwitchViews(this.View);
	}
	
	this.GetEvents = function(){
		this.ShowLoadingScreen();
		var ThisUserIds = "";
		$('.SidebarCal_Checkbox:checked').each(function(){
			ThisUserIds += $(this).attr('UserId')+",";
		});
		
		var TempShowTasks = ($('#CalendarViewTasks').is(':checked') ? "true" : "false");
		
		$.post('/appinclude/action/calendar/get_events.php', {StartDate:this.StartDate, EndDate:this.EndDate, UserIds:ThisUserIds, View:this.View, ShowTasks:TempShowTasks}, function(Data){
			EndGrayOutArea();
			this.Events = new Array();
			InsertMarkupFromAJAX(Data);
			CalendarObject.Display.ProcessDays();
		});
	}
	
	this.ReadEvents = function(EventsJSON){
		//TODO - merge this with existing Events instead of overwriting
		this.Events = eval('(' + EventsJSON + ')');
	}
	
	this.SwitchViews = function(NewView, StartDate){
		this.View = NewView;
		$('.CalendarViewHighlighted').removeClass('CalendarViewHighlighted');
		$('#CalendarSidebarViewSelect_'+NewView).addClass('CalendarViewHighlighted');
		
		if(this.View == 'Month')
			this.Display = new this.MonthView();
		else if(this.View == 'Day')
			this.Display = new this.DayView();
		else if(this.View == 'Agenda')
			this.Display = new this.AgendaView();
		else
			this.Display = new this.WeekView();
		
		var NewDate = this.StartDate;
		if(StartDate != null){
			NewDate = Date.parse(StartDate).toString("MM/dd/yyyy");
		}
		else if(this.StartDate <= Date.today().toString("MM/dd/yyyy") && this.EndDate >= Date.today().toString("MM/dd/yyyy")){
			NewDate = Date.today().toString("MM/dd/yyyy");
		}
		
		this.ChangeDateRange(Date.parse(NewDate));
	}
	
	this.ShowLoadingScreen = function(){
		GrayOutArea('#SidebarBoxWrapper_Calendar');
		
		$("#CalendarWrapper").append("<div class='GrayOutArea CalendarGrayOut'></div>");
		$('.CalendarGrayOut').height($("#CalendarWrapper").height());
		$('.CalendarGrayOut').width($("#CalendarWrapper").width()+15);
		$('.CalendarGrayOut').css('left', '-15px');
		
		$('.CalendarGrayOut').append("<img src='style/default/images/main/loading.gif' class='GrayOutAreaGif' />");
		$('.GrayOutAreaGif').css('position', 'absolute');
		$('.GrayOutAreaGif').css('z-index', '999999999');
		$('.GrayOutAreaGif').css('top', '200px');
		$('.GrayOutAreaGif').css('left', ($('.CalendarGrayOut').width()/2 - 64)+'px');
		
	}
	
	this.SetTaskVisibility = function(SaveSettings){
		//check to see if we need to hide tasks
		var TempShowTasks = $('#CalendarViewTasks').is(':checked');
		//
		
		if(this.View == 'Week'){
			if(!TempShowTasks){
				$('.CalendarTodoRowDiv').hide();
			}
			else{
				$('.CalendarTodoRowDiv').show();
			}
		}
		else if(this.View == 'Day'){
			this.Display.AdjustWidth();
		}
		else if(this.View == 'Month'){
			if(!TempShowTasks){
				$('.CalendarMonthTodo').hide();
			}
			else{
				$('.CalendarMonthTodo').show();
			}
		}
		else if(this.View == 'Agenda'){
			if(!TempShowTasks){
				$('.AgendaTaskElementParent').css('padding-top', '0px');
				$('.AgendaTaskElement').hide();
			}
			else{
				$('.AgendaTaskElementParent').css('padding-top', '12px');
				$('.AgendaTaskElement').show();
			}
		}
		
		var ThisUserIds = "";
		$('.SidebarCal_Checkbox:checked').each(function(){
			ThisUserIds += $(this).attr('UserId')+",";
		});
		
		if(SaveSettings)
			$.post('/appinclude/action/calendar/save_default_settings.php', {UserIds:ThisUserIds, View:this.View, ShowTasks:TempShowTasks}, function(Data){});
	}
	
	//Change an events date/time. Possibly move the event to a new day. Re-sort any impact event days.
	this.ChangeEventDate = function(EventId, OldDate, NewDate){
		ShortNewDate = Date.parse(NewDate).toString("yyyy-MM-dd"); //just the day, not the time
		
		//Find the event in the old date
		Event = null;
		for(i=0; i<this.Events[OldDate]['Events'].length; i++){
			if(this.Events[OldDate]['Events'][i]['EventId'] == parseInt(EventId)){
				OldIndex = i;
				Event = this.Events[OldDate]['Events'][i];
				break;
			}
		}
		
		if(Event == null){
			alert("Error: we couldn't find the event you tried to move");
			return;
		}
		
		//Figure out the new date range
		var TimeDiff = Date.parse(Event['EndDate']).getTime() - Date.parse(Event['StartDate']).getTime();
		Event['StartDate'] = Date.parse(NewDate).toString("yyyy-MM-dd HH:mm:ss");
		Event['EndDate'] = Date.parse(NewDate).add(TimeDiff).milliseconds().toString("yyyy-MM-dd HH:mm:ss");
		
		//Save the change
		this.ShowLoadingScreen();
		var ThisUserIds = "";
		$('.SidebarCal_Checkbox:checked').each(function(){
			ThisUserIds += $(this).attr('UserId')+",";
		});
		
		$.post('/appinclude/action/calendar/move_event.php', {EventId:Event['EventId'], NewStartDate:Event['StartDate'], NewEndDate:Event['EndDate'], StartDate:CalendarObject.StartDate, EndDate:CalendarObject.EndDate, UserIds:ThisUserIds}, function(Data){
			EndGrayOutArea();
			CalendarObject.Events = new Array();
			InsertMarkupFromAJAX(Data);
			CalendarObject.Display.ProcessDays();
		});
		
	}
	
	this.ChangeTodoDate = function(ThisReminderId, NewDate){
		this.ShowLoadingScreen();
		var ThisUserIds = "";
		$('.SidebarCal_Checkbox:checked').each(function(){
			ThisUserIds += $(this).attr('UserId')+",";
		});
		
		$.post('/appinclude/action/calendar/move_todo.php', {ReminderId:ThisReminderId, DueDate:NewDate, StartDate:CalendarObject.StartDate, EndDate:CalendarObject.EndDate, UserIds:ThisUserIds}, function(Data){
			EndGrayOutArea();
			CalendarObject.Events = new Array();
			InsertMarkupFromAJAX(Data);
			CalendarObject.Display.ProcessDays();
		});
	}
	
	//Takes the events for a single day and sorts them.
	this.SortEventsByDate = function(Events){
		//This is a ghetto bubble sort
		var Swapped = true;
		while(Swapped){
			var Swapped = false;
			for(i = 1; i < Events.length; i++){
				if(Events[i-1]['StartDate'] > Events[i]['StartDate']){
					Temp = Events[i-1];
					Events[i-1] = Events[i];
					Events[i] = Temp;
					Swapped = true;
				}
			}
		}
		return Events;
	}
	
	this.ShowBirthdays = function(ThisDate){
		DialogAlert("<div style='min-height:200px;' id='BirthdayDialog'></div>", 550);
		GrayOutArea('#BirthdayDialog', true);
		
		$.post('/appinclude/action/calendar/get_birthdays.php', {Date:ThisDate}, function(Data){
			EndGrayOutArea();
			InsertMarkupFromAJAX(Data);
			ProcessSpecificLink('.BirthdayContact');
		});
	}
	
	/*******************************************************
						Week View
	*******************************************************/
	this.WeekView = function(){
		this.StartHour = 7;
		
		this.PrintCalendar = function(){
			this.StartHour = 7;
			
			var HeaderRow = "<div class='CalendarHeaderRowDiv'>";
			var TodoRow = "<div class='CalendarTodoRowDiv'>";
			var EventRow = "<div class='CalendarEventRowDiv'>";
			
			var Today = Date.parse(CalendarObject.StartDate);
			var EndDate = Date.parse(CalendarObject.EndDate);
			
			while(Today <= EndDate){
				HeaderRow += "<div class='WeekHeader'><div class='WeekHeader_Date'><a href='javascript://' onclick='CalendarObject.SwitchViews(\"Day\", \""+Today.toString("MM/dd/yyyy")+"\")'>"+Today.toString("MMM d")+"</a></div><div class='WeekHeader_DayName'>"+Today.toString('dddd')+"</div></div>";
				
				TodoRow += "<div class='WeekTodoCell' Date='"+Today.toString("MM/dd/yyyy")+"' id='WeekTodoCell_"+Today.toString("yyyy-MM-dd")+"'></div>";
				//var TodoRow = "<div class='CalendarTodoRowDiv' style='width:"+TodoWidth+"px; border:0;'><div style='font-size:17px; color:#666; font-weight:bold; height:36px; line-height:36px; background-color:#ddd; padding-left:10px; border-bottom:1px solid #ccc;'>Task list <span style='float:right; margin-right:10px;'></span></div><div id='DayTodoCell' style='font-size:13px;'></div></div>";
			
				EventRow += "<div class='DayColumn' id='CalendarDay_"+Today.toString("yyyy-MM-dd")+"' Day='"+Today.toString("yyyy-MM-dd")+"'></div>";
				Today = Today.add(1).days();
			}
			EventRow += "</div>";
			HeaderRow += "<br style='clear:both;' /></div>";
			TodoRow += "<br style='clear:both;' /></div>";
			var AccordionRow = "<div class='CalendarAccordion' align='center'><span id='CollapsedTimeNotice'><span id='CollapsedTimeCutoff'></span></span></div>";
			
			
			var FullHTML = HeaderRow+TodoRow+AccordionRow+EventRow+"<div id='TimeDisplayContainer' style='position:relative;'></div>";
			
			
			$('#CalendarWrapper').html(FullHTML);
			
			this.AdjustWidth();
			
			$('.CalendarRangeIncrement').remove();
			$('#CalendarWrapper').append("<a href='javascript://' onclick='CalendarObject.PreviousDateRange();' class='CalendarRangeIncrement' style='position:absolute; left:3px; top:13px;'><img src='/i/app/v3/cal_arrow_left.png' class='CalArrow' width='12' height='28' /></a>");
			$('#CalendarWrapper').append("<a href='javascript://' onclick='CalendarObject.NextDateRange();' class='CalendarRangeIncrement' style='position:absolute; right:3px; top:13px;'><img src='/i/app/v3/cal_arrow_right.png' class='CalArrow' width='12' height='28' /></a>");
		
			$('.DayColumn').bind('click', function(Event){
				var HalfHourHeight = 25;
				var Offset = Event.clientY - /*parseInt($('.DayColumn').css('top')) -*/ $('.DayColumn').offset().top + $(window).scrollTop();
				
				var HalfHours = Math.min(46, Math.round(Offset / HalfHourHeight));
				var Hour = (Math.floor(HalfHours / 2)) % 12;
				if(Hour == 0){
					Hour = 12;
				}
				var TimeDisplay = ""+Hour+":"+(HalfHours % 2 == 0 ? "00" : "30");
				
				if(TimeDisplay == ''){
					
				}
				
				if(HalfHours >= 24)
					TimeDisplay += " pm"
				else
					TimeDisplay += " am";
				
				EventObject.NewEventDialog($(this).attr('day'), TimeDisplay)
			});
			
			$('.WeekTodoCell').hover(function(){
				$(this).find('.WeekTodoMouseover').remove();
				$(this).append("<div style='position:absolute; bottom:1px; left:18px;' class='WeekTodoMouseover'><a href='javascript://' onclick='ReminderObject.NewReminder(null, \""+$(this).attr('Date')+"\");' class='IconSprite IconSprite-add_translucent'></a><a href='javascript://' style='font-size:10px; color:#999; font-weight:normal' class='NoUnderline' onclick='ReminderObject.NewReminder(null, \""+$(this).attr('Date')+"\");'> New task</a></div>");
				$('.WeekTodoMouseover').css('left', ($('.WeekTodoMouseover').parent().width() - $('.WeekTodoMouseover').width())/ 2);
			}, function(){
				$(this).find('.WeekTodoMouseover').remove();
			});
			
			CalendarObject.SetTaskVisibility();
		}
		
		this.AdjustWidth = function(){
			var TotalWidth = $('#CalendarWrapper').width();
			var ColWidth = Math.floor(TotalWidth/7);
			var LastColWidth = ColWidth + TotalWidth - 7*ColWidth;
			$('.WeekHeader, .WeekTodoCell, .DayColumn').width(ColWidth-1);
			$('.WeekHeader:last, .WeekTodoCell:last, .DayColumn:last').width(LastColWidth-1);
			$('.CalendarWeekEvent').each(function(){
				Left = (ColWidth - 30) / 4 * Math.min(3, parseInt($(this).attr('LeftPosition')));
				$(this).css('left', Left);
				$(this).width(ColWidth-8-parseInt($(this).css('left')));
			});
			$('.CalendarWeekEvent').draggable("option", "grid",[ColWidth, 25] );
			$('.TodoAgendaLine').draggable("option", "grid",[ColWidth, 25] );
			
			$('.WeekTodoCell').css('height', '');
			var MaxHeight = 0;
			$('.WeekTodoCell').each(function(){
				MaxHeight = Math.max(MaxHeight, parseInt($(this).height()+5));
			});
			$('.WeekTodoCell').height(MaxHeight);
		}
		
		this.ProcessDays = function(){
			$('.CalendarEvent').remove();
			$('.WeekTodoCell').html('');
			
			var EndDate = Date.parse(CalendarObject.EndDate);
			var StartDate = Date.parse(CalendarObject.StartDate);
			Today = StartDate;
				
			while(Today <= EndDate){
				//Loop through all the events for the current day
				try{
					var TodaysEvents = CalendarObject.Events[Today.toString("yyyy-MM-dd")]['Events'];
					var Todos = CalendarObject.Events[Today.toString("yyyy-MM-dd")]['Todos'];
					var Birthdays = CalendarObject.Events[Today.toString("yyyy-MM-dd")]['Birthdays'];
					this.PrintEvents(TodaysEvents, Todos, Birthdays, Today.toString("yyyy-MM-dd"));
				}catch(err){
					//There aren't any events for today
				}
				
				Today = Today.add(1).days();
			}
			
			//Apply event listenrs and all the stuff
			
			//Set up the calendar to condense the early hours correctly
			if(this.StartHour <= 2)
				this.StartHour = 0;
			
			if(this.StartHour == 0){
				$('.CalendarAccordion').hide();
			}
			
			$('#CollapsedTimeCutoff').html("<a href='javascript://' onclick='CalendarObject.Display.ShowFullDays();' style='color:#999999;'>Also show midnight through "+this.StartHour+":00 am</a>");
			this.PrintHours(this.StartHour);
			
			$('.DayColumn').css('top', "-"+(this.StartHour*50)+"px");

			//Set the listeners for all the events
			$('.CalendarWeekEvent').bind('click', function(e){
				EventObject.EditEventDialog($(this).attr('EventId'));
				e.stopPropagation();
			});
			
			$('.CalendarWeekEvent').draggable({
				grid: [113, 25],
				zIndex: 99999,
				contaiment: 'parent',
				distance:20,
				stop:function(){
					//If the drag highlighted something on the page, we should un-highlight it
					CalendarObject.Display.ProcessDays();
				}
			});
			$('.DayColumn').droppable({
				accept: ".CalendarWeekEvent",
				drop:function(event, ui){

					Day = $(this).attr("Day");
					Minutes = Math.round(ui.position['top'] % 50 * 6 / 5);
					if(Minutes < 10)
						Minutes = "0"+Minutes;
					
					Hour = Math.floor(ui.position['top']/50);
					if(Hour < 10)
						Hour = "0"+Hour;
					
					CalendarObject.ChangeEventDate(ui.draggable.attr('EventId'), ui.draggable.attr('Date'), Day+" "+Hour+":"+Minutes);
					
					//Accept the dragged event
				}
			});
			
			//tasks
			$('.TodoAgendaLine').draggable({
				grid: [112, 10],
				zIndex: 99999,
				contaiment: 'parent',
				distance:10,
				stop:function(){
					//If the drag highlighted something on the page, we should un-highlight it
					CalendarObject.Display.ProcessDays();
				}
			});
			
			$('.WeekTodoCell').droppable({
				accept: ".TodoAgendaLine",
				drop:function(event, ui){
					Day = $(this).attr("Date");
					CalendarObject.ChangeTodoDate(ui.draggable.attr('ReminderId'), Day);
				}
			});
			
			CalendarObject.SetTaskVisibility();
			
			this.AdjustWidth();
		}
		
		this.PrintHours = function(StartHour){
			//Hide the old times
			$('.DayTimeDisplay').remove();
			
			if(StartHour != 0){
				$('#TimeDisplayContainer').append("<div class='DayTimeDisplay FirstDayTimeDisplay' style='top:-1248px;'>12am</div>");
			}
			
			//Print the times
			var HourCount = 0;
			for(i=StartHour; i< 25; i++){
				if(CalendarObject.UsesInternationalTimeFormat == 1){
					ampm = ":00";
					TempTime = i;
					
				}
				else{
					ampm = (i < 12 || i > 23 ? "am" : "pm");
					TempTime = i%12;
					if(TempTime == 0)
						TempTime = 12;
				}
				$('#TimeDisplayContainer').append("<div class='DayTimeDisplay' style='top:-"+(1200-(HourCount*50-7))+"px;'>"+TempTime+ampm+"</div>");
				HourCount++;
			}
		}
		
		this.PrintEvents = function(Events, Todos, Birthdays, ThisDate){
			var CurrentEvents = new Array();
			var TakenPositions = new Array();
			
			this.PrintTodos(Todos, Birthdays, ThisDate);
			
			for(i=0; i<Events.length; i++){
				
				StartTime = Date.parse(Events[i]['StartDate']).getTime();
				//Loop through CurrentEvents and remove any that have already ended
				jQuery.each(CurrentEvents, function(Index, Value){
					if(Value && StartTime >= Date.parse(Value['EndDate']).getTime()){
						TakenPositions[Value['LeftPosition']] = 'off';
						CurrentEvents[Index] = false;
					}
				});
				//remove all ended events from CurrentEvents
				CurrentEvents = jQuery.grep(CurrentEvents, function(value) {
				  return value;
				});
				
				//Figure out what the left-most position is for this event
				LeftPosition = CurrentEvents.length;
				for(j=LeftPosition; j<TakenPositions.length; j++){
					if(TakenPositions[j] == 'on'){
						LeftPosition = j;
					}
				}
				Events[i]['LeftPosition'] = LeftPosition;
				CurrentEvents.push(Events[i]);
				TakenPositions[LeftPosition] = 'on';
				//Print the event
				this.PrintEvent(Events[i], LeftPosition);
				
				//Check to see if this event is before the current start position
				if(parseInt(Date.parse(Events[i]['StartDate']).toString("H")) < this.StartHour){
					this.StartHour = parseInt(Date.parse(CurrentEvents[i]['StartDate']).toString("H"));
				}
			}
		}
		
		this.PrintEvent = function(Event, LeftPosition){
			EventStart = Date.parse(Event['StartDate']);
			EventEnd = Date.parse(Event['EndDate']);
			DifferenceInMinutes = Math.round((EventEnd - EventStart)/60/1000);
			DifferenceInPixels = DifferenceInMinutes * 50/60 - 2; //we subtract 2 because there's a border
			var TimeFormat = (CalendarObject.UsesInternationalTimeFormat == 1 ? "HH:mm" : "h:mm");
			
			Offset = parseInt(EventStart.toString("H"))*50 + Math.round(parseInt(EventStart.toString(" m"))*50/60);
			
			//We'll never condense something by more than 60 pixels
			Left = Math.min(60, LeftPosition * 15);
			Width = 104 - Left;
			
			$('#CalendarDay_'+EventStart.toString("yyyy-MM-dd")).append(
				"<div id='CalendarEvent_"+Event['EventId']+"' class='CalendarEvent CalendarWeekEvent CalendarUserColor_"+Event['UserId']+"' style='top:"+Offset+"px; left:"+Left+"px; width:"+Width+"px; height:"+DifferenceInPixels+"px; z-index:"+LeftPosition+";'"+
				"EventId='"+Event['EventId']+"' Date='"+EventStart.toString("yyyy-MM-dd")+"' title='Click to view and edit details' LeftPosition='"+LeftPosition+"'>"+
				Event['Name']+"<br />"+
				"<span style='color:#dddddd; text-shadow:none; font-size:10px;' class='EventTimeDisplay'>"+EventStart.toString(TimeFormat)+" - "+EventEnd.toString(TimeFormat)+"</span></div>");
		}
		
		this.ShowFullDays = function(){
			this.StartHour = 0;
			this.PrintHours(this.StartHour);
			var Top = parseInt(str_replace ("px", "", $('.DayColumn').css('top')));
			var Speed = 5;
			this.SlideDownEvents(Speed, Top);
			
			$('.CalendarAccordion').slideUp('fast');
		}
		
		this.SlideDownEvents = function(Speed, Top){
			NewTop = Math.min(0,(Top+Speed))
			if(Top == NewTop)
				return;
			
			$('.DayColumn').css('top', ""+NewTop+"px");
			setTimeout("CalendarObject.Display.SlideDownEvents("+(Speed+10)+", "+NewTop+")");
		}
		
		this.PrintTodos = function(Todos, Birthdays, ThisDate){
			var MultipleUsers = $('.SidebarCal_Checkbox:checked').length > 1;
			var Print = "";
			
			if(Todos.length > 0){	
				var UserId = 0;
				for(i=0; i<Todos.length; i++){
					ThisTodo = Todos[i]
					
					if(ThisTodo['Access'] == 'Write'){
						var OnCheck = "ReminderObject.CheckTodo(this);";
						var OnEdit = "ReminderObject.EditReminder(this)";
					}
					else{
						var OnCheck = "DialogAlert(\"You do not have permission to modify this task\")";
						var OnEdit = "DialogAlert(\"You do not have permission to modify this task\")";
					}
					
					
					if(MultipleUsers && ThisTodo['UserId'] != UserId){
						
						Print += "<div class='CalendarUserColor_"+ThisTodo['UserId']+" CalendarTodoHeader'>"+$('#CalendarUserSName_'+ThisTodo['UserId']).html()+" tasks</div>";
						UserId = ThisTodo['UserId'];
					}
					
					Print += "<div class='TodoAgendaLine' style='margin:2px; cursor:move;' ReminderId='"+ThisTodo['ReminderId']+"'>"+
						"<a href='javascript://'><img src='/i/app/checkbox"+(ThisTodo['IsChecked'] == 1 ? "_checked" : "")+".png' IsChecked='"+(ThisTodo['IsChecked'] == 1 ? "1" : "0")+"'  onclick='"+OnCheck+"'"+
							"class='Icon TodoIconBig_"+ThisTodo['ReminderId']+" TodoIcon_"+ThisTodo['ReminderId']+"' ReminderId='"+ThisTodo['ReminderId']+"' onmouseover='ReminderObject.HoverDashboardCheckbox(this, "+ThisTodo['ReminderId']+");' onmouseout='ReminderObject.EndHoverDashboardCheckbox(this, "+ThisTodo['ReminderId']+");' /></a>"+
						"<a href='javascript://' onclick='"+OnEdit+"' title='Click to edit this task' "+ThisTodo['EditAttributes']+""+
						"class='NoUnderline TodoLink TodoLink_"+ThisTodo['ReminderId']+" "+(ThisTodo['IsChecked'] == 1 ? "CheckedTodo" : "")+"' style='font-size:line-height:17px;'>"+ThisTodo['Name']+"</a>"+
						(ThisTodo['ContactId'] ? 
							"<div style='font-size:10px;' class='TodoContactInfo TodoContactLinkText_"+ThisTodo['ReminderId']+" "+(ThisTodo['IsChecked'] == 1 ? "GrayedOutTodoContactInfo" : "")+"'><a href='/app/View_Contact?ContactId="+ThisTodo['ContactId']+"' class='NoUnderline CalendarTodoContactLink'>"+ThisTodo['ContactName']+"</a></div>"
						 : "")+
						
						"</div>";
				}
			}
			
			
			if(Birthdays.length > 0){
				if(Birthdays.length == 1){
					ThisBirthday = Birthdays[0];
					Print += "<div style='padding:2px; margin-top:3px;'><span class='IconSprite IconSprite-cake'></span> <a href='/app/View_Contact?ContactId="+ThisBirthday['ContactId']+"' class='CalendarTodoContactLink NoUnderline' style='color:#666;'>"+
							ThisBirthday['Salutation']+" "+ThisBirthday['FirstName']+" "+ThisBirthday['MiddleName']+" "+ThisBirthday['LastName']+" "+ThisBirthday['Suffix']+" "+(ThisBirthday['CompanyName'] != 'NULL' ? ThisBirthday['CompanyName'] : "")+" "+"</a></div>"+
						"";
				}
				else{
					Print += "<div style='padding:2px; margin-top:3px;'><span class='IconSprite IconSprite-cake'></span> <a href='javascript://' onclick='CalendarObject.ShowBirthdays(\""+ThisDate+"\");' class='CalendarTodoContactLink NoUnderline' style='color:#666;'>"+
							Birthdays.length+" birthdays"+"</a></div>"+
						"";
				}
			}
			

			$('#WeekTodoCell_'+ThisDate).html(Print);
			
			ProcessSpecificLink('.CalendarTodoContactLink');
		}
		
		this.PrintBirthdays = function(Birthdays, Date){
			$('#WeekTodoCell_'+Todos[0]['DueDate']).html(Print);
		}
		
		this.Print = function(){
			var PrintWindow = window.open("/downloads/calendar/print.php?Type=Week","printcal",'width=1000,height=650');
		}
	}
	
	/*******************************************************
						Day View
	*******************************************************/
	this.DayView = function(){
		this.StartHour = 7;
		this.ColWidth = 445; //the width of the event column
		
		this.PrintCalendar = function(){
			this.StartHour = 7;
			
			var Today = Date.parse(CalendarObject.StartDate);
			var EndDate = Date.parse(CalendarObject.EndDate);
			
			var HeaderRow = "<div class='CalendarHeaderRowDiv'><div class='WeekHeader'><div class='WeekHeader_Date' style='font-size:22px;  height:30px; line-height:35px;'>"+Today.toString("dddd MMMM dS, yyyy")+"</div><br style='clear:both;' /></div></div>";
			var TodoRow = "<div class='CalendarTodoRowDiv' style=' border:0;'><div style='font-size:17px; color:#666; font-weight:bold; height:36px; line-height:36px; background-color:#ddd; padding-left:10px; border-bottom:1px solid #ccc;'>Task list <span style='float:right; margin-right:10px;'><a href='javascript://' onclick='ReminderObject.NewReminder(null, \""+Today.toString('MM/dd/yyyy')+"\");' class='IconSprite IconSprite-add_translucent'></a><a href='javascript://' style='font-size:13px; color:#999; font-weight:normal' class='NoUnderline' onclick='ReminderObject.NewReminder(null, \""+Today.toString('MM/dd/yyyy')+"\");'> New task</a></span></div><div id='DayTodoCell' style='font-size:13px;'></div></div>";
			
				
			var EventRow = "<div class='CalendarEventRowDiv' ><div class='DayColumn' id='CalendarDay_"+Today.toString("yyyy-MM-dd")+"' Day='"+Today.toString("yyyy-MM-dd")+"'></div></div>";
			
			
			//HeaderRow += "";
			//TodoRow += "<br style='clear:both;' /></div>";
			var AccordionRow = "<div class='CalendarAccordion' align='center'><span id='CollapsedTimeNotice'><span id='CollapsedTimeCutoff'></span></span></div>";
			
			//var FullHTML = "<table cellspacing='0' cellpadding='0' class='CalendarWrapperTable' style=''><tr>"+HeaderRow+"</tr><tr>"+TodoRow+"</tr><tr style='border-left:1px solid white;'>"+AccordionRow+"</tr><tr style='overflow:hidden;'>"+EventRow+"</tr></table><div id='TimeDisplayContainer' style='position:relative;'></div>";
			
			
			
			var FullHTML = HeaderRow+"<table width='100%' cellspacing='0' cellpadding='0'><tr><td valign='top' style='background-color:#eee; border:0;'>"+
							TodoRow+"</td><td valign='top' class='DayCalendarTodoCell'>"+
							AccordionRow+EventRow+"<div id='TimeDisplayContainer' style='position:relative;'></div></td></tr></table>";
			
			$('#CalendarWrapper').html(FullHTML);
			
			$('.CalendarRangeIncrement').remove();
			$('#CalendarWrapper').append("<a href='javascript://' onclick='CalendarObject.PreviousDateRange();' class='CalendarRangeIncrement' style='position:absolute; left:3px; top:13px;'><img src='/i/app/v3/cal_arrow_left.png' class='CalArrow' width='12' height='28' /></a>");
			$('#CalendarWrapper').append("<a href='javascript://' onclick='CalendarObject.NextDateRange();' class='CalendarRangeIncrement' style='position:absolute; right:3px; top:13px;'><img src='/i/app/v3/cal_arrow_right.png' class='CalArrow' width='12' height='28' /></a>");
		
			$('.DayColumn').bind('click', function(Event){
				var HalfHourHeight = 25;
				var Offset = Event.clientY - /*parseInt($('.DayColumn').css('top')) -*/ $('.DayColumn').offset().top + $(window).scrollTop();
				
				var HalfHours = Math.min(46, Math.round(Offset / HalfHourHeight));
				var Hour = (Math.floor(HalfHours / 2)) % 12;
				if(Hour == 0){
					Hour = 12;
				}
				var TimeDisplay = ""+Hour+":"+(HalfHours % 2 == 0 ? "00" : "30");
				
				if(TimeDisplay == ''){
					
				}
				
				if(HalfHours >= 24)
					TimeDisplay += " pm"
				else
					TimeDisplay += " am";
				
				EventObject.NewEventDialog($(this).attr('day'), TimeDisplay)
			});
			
			CalendarObject.SetTaskVisibility();
		}
		
		this.AdjustWidth = function(){
			var TotalWidth = $('#BodyMain').width() - $('#SidebarBoxWrapper_Calendar').width()-2;
			
			var ShowTasks = $('#CalendarViewTasks').is(':checked');
			if(ShowTasks){
				$('.CalendarTodoRowDiv').show();
				var TodoWidth = Math.floor(TotalWidth *.4);
				var EventWidth = TotalWidth - TodoWidth;
			}
			else{
				$('.CalendarTodoRowDiv').hide();
				var TodoWidth = 0;
				var EventWidth = TotalWidth;
			}
			
			$('.CalendarTodoRowDiv').width(TodoWidth-1);
			$('.WeekHeader').width(TotalWidth-1);
			$('.DayColumn').width(EventWidth);
			
			$('.CalendarWeekEvent').each(function(){
				Left = (EventWidth - 30) / 4 * Math.min(3, parseInt($(this).attr('LeftPosition')));
				$(this).css('left', Left+40);
				$(this).width(EventWidth-15-parseInt($(this).css('left')));
			});
		}
		
		this.ProcessDays = function(){
			$('.CalendarEvent').remove();
			$('.WeekTodoCell').html('');

			var EndDate = Date.parse(CalendarObject.EndDate);
			var StartDate = Date.parse(CalendarObject.StartDate);
			Today = StartDate;
				
			//For each user, loop through each day on the calendar
			while(Today <= EndDate){
				//Loop through all the events for the current day
				try{
					
					var TodaysEvents = CalendarObject.Events[Today.toString("yyyy-MM-dd")]['Events'];
					var Todos = CalendarObject.Events[Today.toString("yyyy-MM-dd")]['Todos'];
					var Birthdays = CalendarObject.Events[Today.toString("yyyy-MM-dd")]['Birthdays'];
					this.PrintEvents(TodaysEvents, Todos, Birthdays, Today.toString("yyyy-MM-dd"));
					
				}catch(err){
					//There aren't any events for today
				}
				
				Today = Today.add(1).days();
			}
			
			//Apply event listenrs and all the stuff
			
			//Set up the calendar to condense the early hours correctly
			if(this.StartHour <= 2)
				this.StartHour = 0;
			
			if(this.StartHour == 0){
				$('.CalendarAccordion').hide();
			}
			
			$('#CollapsedTimeCutoff').html("<a href='javascript://' onclick='CalendarObject.Display.ShowFullDays();' style='color:#999999;'>Also show midnight through "+this.StartHour+":00 am</a>");
			this.PrintHours(this.StartHour);
			
			$('.DayColumn').css('top', "-"+(this.StartHour*50)+"px");

			//Set the listeners for all the events
			$('.CalendarWeekEvent').bind('click', function(e){
				EventObject.EditEventDialog($(this).attr('EventId'));
				e.stopPropagation();
			});
			
			$('.CalendarWeekEvent').draggable({
				grid: [this.ColWidth, 25],
				zIndex: 99999,
				contaiment: 'parent',
				distance:20,
				stop:function(){
					//If the drag highlighted something on the page, we should un-highlight it
					/*sel=window.getSelection();
					if(sel && sel.removeAllRanges)
						sel.removeAllRanges() ;
					*/
					CalendarObject.Display.ProcessDays();
				}
			});
			$('.DayColumn').droppable({
				accept: ".CalendarWeekEvent",
				drop:function(event, ui){

					Day = $(this).attr("Day");
					Minutes = Math.round(ui.position['top'] % 50 * 6 / 5);
					if(Minutes < 10)
						Minutes = "0"+Minutes;
					
					Hour = Math.floor(ui.position['top']/50);
					if(Hour < 10)
						Hour = "0"+Hour;
					
					CalendarObject.ChangeEventDate(ui.draggable.attr('EventId'), ui.draggable.attr('Date'), Day+" "+Hour+":"+Minutes);
					
					//Accept the dragged event
				}
			});
			
			CalendarObject.SetTaskVisibility();
			this.AdjustWidth();
		}
		
		this.PrintHours = function(StartHour){
			//Hide the old times
			$('.DayTimeDisplay').remove();
			
			if(StartHour != 0){
				//$('#TimeDisplayContainer').append("<div class='DayTimeDisplay' style='left: 0px; top:-1248px;'>12am</div>");
			}
			
			//Print the times
			var HourCount = 0;
			for(i=StartHour; i< 25; i++){
				if(CalendarObject.UsesInternationalTimeFormat == 1){
					ampm = ":00";
					TempTime = i;
					
				}
				else{
					ampm = (i < 12 || i > 23 ? "am" : "pm");
					TempTime = i%12;
					if(TempTime == 0)
						TempTime = 12;
				}
				$('#TimeDisplayContainer').append("<div class='DayTimeDisplay' style='top:-"+(1200-(HourCount*50-7))+"px;'>"+TempTime+ampm+"</div>");
				HourCount++;
			}
		}
		
		this.PrintEvents = function(Events, Todos, Birthdays, ThisDate){
			var CurrentEvents = new Array();
			var TakenPositions = new Array();
			
			this.PrintTodos(Todos, Birthdays, ThisDate);
			
			for(i=0; i<Events.length; i++){
				
				StartTime = Date.parse(Events[i]['StartDate']).getTime();
				//Loop through CurrentEvents and remove any that have already ended
				jQuery.each(CurrentEvents, function(Index, Value){
					if(Value && StartTime >= Date.parse(Value['EndDate']).getTime()){
						TakenPositions[Value['LeftPosition']] = 'off';
						CurrentEvents[Index] = false;
					}
				});
				//remove all ended events from CurrentEvents
				CurrentEvents = jQuery.grep(CurrentEvents, function(value) {
				  return value;
				});
				
				//Figure out what the left-most position is for this event
				LeftPosition = CurrentEvents.length;
				for(j=LeftPosition; j<TakenPositions.length; j++){
					if(TakenPositions[j] == 'on'){
						LeftPosition = j;
					}
				}
				
				Events[i]['LeftPosition'] = LeftPosition;
				CurrentEvents.push(Events[i]);
				TakenPositions[LeftPosition] = 'on';
				
				//Print the event
				this.PrintEvent(Events[i], LeftPosition);
				
				//Check to see if this event is before the current start position
				if(parseInt(Date.parse(Events[i]['StartDate']).toString("H")) < this.StartHour){
					this.StartHour = parseInt(Date.parse(CurrentEvents[i]['StartDate']).toString("H"));
				}
			}
		}
		
		this.PrintEvent = function(Event, LeftPosition){
			var EventStart = Date.parse(Event['StartDate']);
			var EventEnd = Date.parse(Event['EndDate']);
			var DifferenceInMinutes = Math.round((EventEnd - EventStart)/60/1000);
			var DifferenceInPixels = DifferenceInMinutes * 50/60 - 2; //we subtract 2 because there's a border
			var TimeFormat = (CalendarObject.UsesInternationalTimeFormat == 1 ? "HH:mm" : "h:mm");
			
			var Offset = parseInt(EventStart.toString("H"))*50 + Math.round(parseInt(EventStart.toString(" m"))*50/60);
			
			//We'll never condense something by more than 60 pixels
			var Indent = 35;
			var Left = Math.min(360, LeftPosition * 60)+Indent;
			var Width = this.ColWidth - Left - 20;
			
			$('#CalendarDay_'+EventStart.toString("yyyy-MM-dd")).append(
				"<div id='CalendarEvent_"+Event['EventId']+"' class='CalendarEvent CalendarWeekEvent CalendarUserColor_"+Event['UserId']+"' style='top:"+Offset+"px; left:"+Left+"px; width:"+Width+"px; height:"+DifferenceInPixels+"px; z-index:"+LeftPosition+";'"+
				"EventId='"+Event['EventId']+"' Date='"+EventStart.toString("yyyy-MM-dd")+"' title='Click to view and edit details' LeftPosition='"+LeftPosition+"'>"+
				Event['Name']+"<br />"+
				"<span style='color:#dddddd; text-shadow:none; font-size:10px;' class='EventTimeDisplay'>"+EventStart.toString(TimeFormat)+" - "+EventEnd.toString(TimeFormat)+"</span></div>");
		}
		
		this.ShowFullDays = function(){
			this.StartHour = 0;
			this.PrintHours(this.StartHour);
			var Top = parseInt(str_replace ("px", "", $('.DayColumn').css('top')));
			var Speed = 5;
			this.SlideDownEvents(Speed, Top);
			
			$('.CalendarAccordion').slideUp('fast');
		}
		
		this.SlideDownEvents = function(Speed, Top){
			NewTop = Math.min(0,(Top+Speed))
			if(Top == NewTop)
				return;
			
			$('.DayColumn').css('top', ""+NewTop+"px");
			setTimeout("CalendarObject.Display.SlideDownEvents("+(Speed+10)+", "+NewTop+")");
		}
		
		this.PrintTodos = function(Todos, Birthdays, ThisDate){
			var MultipleUsers = $('.SidebarCal_Checkbox:checked').length > 1;
			var Print = "";
			var UserId = 0;
			
			if(Todos.length > 0){	
				for(i=0; i<Todos.length; i++){
					ThisTodo = Todos[i];
					
					if(ThisTodo['Access'] == 'Write'){
						var OnCheck = "ReminderObject.CheckTodo(this);";
						var OnEdit = "ReminderObject.EditReminder(this)";
					}
					else{
						var OnCheck = "DialogAlert(\"You do not have permission to modify this task\")";
						var OnEdit = "DialogAlert(\"You do not have permission to modify this task\")";
					}
					
					if(MultipleUsers && ThisTodo['UserId'] != UserId){
						
						Print += "<div class='CalendarUserColor_"+ThisTodo['UserId']+" CalendarTodoHeader' style='"+(i > 0 ? "margin-top:15px;" : "")+"'>"+$('#CalendarUserSName_'+ThisTodo['UserId']).html()+" tasks</div>";
						UserId = ThisTodo['UserId'];
					}
					
					Print += "<div class='TodoAgendaLine' style='margin:2px; margin-left:10px;'>"+
						"<a href='javascript://'><img src='/i/app/checkbox"+(ThisTodo['IsChecked'] == 1 ? "_checked" : "")+".png' IsChecked='"+(ThisTodo['IsChecked'] == 1 ? "1" : "0")+"'  onclick='"+OnCheck+"'"+
							"class='Icon TodoIconBig_"+ThisTodo['ReminderId']+" TodoIcon_"+ThisTodo['ReminderId']+"' ReminderId='"+ThisTodo['ReminderId']+"' onmouseover='ReminderObject.HoverDashboardCheckbox(this, "+ThisTodo['ReminderId']+");' onmouseout='ReminderObject.EndHoverDashboardCheckbox(this, "+ThisTodo['ReminderId']+");' /></a>"+
						"<a href='javascript://' onclick='"+OnEdit+"' title='Click to edit this task' "+ThisTodo['EditAttributes']+""+
						"class='NoUnderline TodoLink TodoLink_"+ThisTodo['ReminderId']+" "+(ThisTodo['IsChecked'] == 1 ? "CheckedTodo" : "")+"' style='font-size:line-height:17px;'>"+ThisTodo['Name']+"</a>"+
						(ThisTodo['ContactId'] ? 
							"<div style='font-size:10px;' class='TodoContactInfo TodoContactLinkText_"+ThisTodo['ReminderId']+" "+(ThisTodo['IsChecked'] == 1 ? "GrayedOutTodoContactInfo" : "")+"'>Linked to <a href='/app/View_Contact?ContactId="+ThisTodo['ContactId']+"' class='NoUnderline CalendarTodoContactLink'>"+ThisTodo['ContactName']+"</a></div>"
						 : "")+
						
						"</div>";
				}
				
				Print += "<br style='clear:both;' />";
				
				
			}
			
			if(Birthdays.length > 0){
				if(Birthdays.length == 1){
					ThisBirthday = Birthdays[0]
					Print += "<div style='padding:2px; margin-top:3px;'><span class='IconSprite IconSprite-cake'></span> <a href='/app/View_Contact?ContactId="+ThisBirthday['ContactId']+"' class='CalendarTodoContactLink NoUnderline' style='color:#666;'>"+
							ThisBirthday['Salutation']+" "+ThisBirthday['FirstName']+" "+ThisBirthday['MiddleName']+" "+ThisBirthday['LastName']+" "+ThisBirthday['Suffix']+" "+(ThisBirthday['CompanyName'] != 'NULL' ? ThisBirthday['CompanyName'] : "")+" "+"</a></div>"+
						"";
				}
				else{
					Print += "<div style='padding:2px; margin-top:3px;'><span class='IconSprite IconSprite-cake'></span> <a href='javascript://' onclick='CalendarObject.ShowBirthdays(\""+ThisDate+"\");' class='CalendarTodoContactLink NoUnderline' style='color:#666;'>"+
							Birthdays.length+" birthdays"+"</a></div>"+
						"";
				}
			}
			
			$('#DayTodoCell').html(Print);
				
			ProcessSpecificLink('.CalendarTodoContactLink');
		}
		
		this.Print = function(){
			var PrintWindow = window.open("/downloads/calendar/print.php?Type=Day","printcal",'width=1000,height=650');
		}
	}
	
	/*******************************************************
						Month View
	*******************************************************/
	this.MonthView = function(){
		this.PrintCalendar = function(){
			var HeaderRow = "<div class='CalendarHeaderRowDiv'><div class='WeekHeader'><div class='WeekHeader_Date' style='font-size:22px;  height:30px; line-height:35px;'>"+Date.parse(CalendarObject.StartDate).toString("MMMM yyyy")+"</div><br style='clear:both;' /></div></div>"+
				"<div class='MonthDayName' align='center'>Sunday</div>"+
				"<div class='MonthDayName' align='center'>Monday</div>"+
				"<div class='MonthDayName' align='center'>Tuesday</div>"+
				"<div class='MonthDayName' align='center'>Wednesday</div>"+
				"<div class='MonthDayName' align='center'>Thursday</div>"+
				"<div class='MonthDayName' align='center'>Friday</div>"+
				"<div class='MonthDayName' align='center'>Saturday</div>";
			
			var EventRow = "<div class='CalendarEventRowDiv'>";
			
			var Today = Date.parse(CalendarObject.StartDate);
			var EndDate = Date.parse(CalendarObject.EndDate);
			
			if(!Today.is().sunday())
				Today = Today.last().sunday();
			if(!EndDate.is().saturday())
				EndDate = EndDate.next().saturday();
			
			var Count = 1;
			while(Today <= EndDate){
				var IsCurrentMonth = Today.toString('MM') == Date.parse(CalendarObject.StartDate).toString("MM");
				EventRow += "<div class='DayColumn' id='CalendarDay_"+Today.toString("yyyy-MM-dd")+"' Day='"+Today.toString("yyyy-MM-dd")+"' style='background-image:none; border-bottom:1px solid #ccc; height:110px; "+(IsCurrentMonth ? "" : "background-color:#ddd;")+"'>"+
							"<div align='right'><a href='javascript://' class='NoUnderline' onclick='CalendarObject.SwitchViews(\"Day\", \""+Today.toString("MM/dd/yyyy")+"\")' style='font-size:11px; margin-top:3px; margin-right:3px; "+(IsCurrentMonth ? "font-weight:bold; color:#666;" : "color:#aaa;")+"'>"+Today.toString(" d")+"</a></div>"+
							"</div>";
				Today = Today.add(1).days();
				Count ++;
			}
			
			EventRow += "</div>";
			
			var FullHTML = HeaderRow+EventRow+"<div id='TimeDisplayContainer' style='position:relative;'></div>";
			
			$('#CalendarWrapper').html(FullHTML);
			this.AdjustWidth();
			
			$('.CalendarRangeIncrement').remove();
			$('#CalendarWrapper').append("<a href='javascript://' onclick='CalendarObject.PreviousDateRange();' class='CalendarRangeIncrement' style='position:absolute; left:3px; top:13px;'><img src='/i/app/v3/cal_arrow_left.png' class='CalArrow' width='12' height='28' /></a>");
			$('#CalendarWrapper').append("<a href='javascript://' onclick='CalendarObject.NextDateRange();' class='CalendarRangeIncrement' style='position:absolute; right:3px; top:13px;'><img src='/i/app/v3/cal_arrow_right.png' class='CalArrow' width='12' height='28' /></a>");
		
			$('.DayColumn').bind('click', function(Event){
				EventObject.NewEventDialog($(this).attr('day'))
			});
		}
		
		this.ProcessDays = function(){
			$('.CalendarEvent').remove();

			//var StartDate = Date.parse(CalendarObject.StartDate);
			
			var Today = Date.parse(CalendarObject.StartDate);
			var EndDate = Date.parse(CalendarObject.EndDate);
			
			if(!Today.is().sunday())
				Today = Today.last().sunday();
			if(!EndDate.is().saturday())
				EndDate = EndDate.next().saturday();
			
			//loop through each day on the calendar
			while(Today <= EndDate){
				//Loop through all the events for the current day
				try{
					var TodaysEvents = CalendarObject.Events[Today.toString("yyyy-MM-dd")]['Events'];
					var Todos = CalendarObject.Events[Today.toString("yyyy-MM-dd")]['Todos'];
					var Birthdays = CalendarObject.Events[Today.toString("yyyy-MM-dd")]['Birthdays'];
					this.PrintEvents(TodaysEvents, Todos, Birthdays);
				}catch(err){
					//There aren't any events for today
				}
				
				Today = Today.add(1).days();
			}
			
			//Apply event listenrs and all the stuff
			
			//Set the listeners for all the events
			$('.CalendarMonthEvent').bind('click', function(e){
				EventObject.EditEventDialog($(this).attr('EventId'));
				e.stopPropagation();
			});
			
			$('.CalendarMonthTodo').bind('click', function(e){
				if($(this).attr('Access') == 'Write'){
					ReminderObject.EditReminder(this);
				}
				else{
					DialogAlert("You do not have permission to modify this task");
				}
				
				e.stopPropagation();
			});
			
			$('.CalendarMonthItem').draggable({
				grid: [112, 20],
				zIndex: 99999,
				contaiment: 'parent',
				distance:20,
				stop:function(){
				
					CalendarObject.Display.ProcessDays();
				}
			});
			$('.DayColumn').droppable({
				accept: ".CalendarMonthItem",
				drop:function(event, ui){
					if(ui.draggable.hasClass('CalendarMonthTodo')){
						if(ui.draggable.attr('Access') != 'Write'){
							DialogAlert("You don't have access to modify this task");
						}
						else{
							CalendarObject.ChangeTodoDate(ui.draggable.attr('ReminderId'), $(this).attr("Day"));
						}
					}
					else{
						var NewDate = $(this).attr("Day")+" "+ui.draggable.attr("Hour")+":"+ui.draggable.attr("Minute");
						CalendarObject.ChangeEventDate(ui.draggable.attr('EventId'), ui.draggable.attr('Date'), NewDate);
					}
					
				}
			});
			
			CalendarObject.SetTaskVisibility();
			this.AdjustWidth();
		}
		
		this.AdjustWidth = function(){
			$('.WeekHeader').width(0);
			
			var TotalWidth = $('#CalendarWrapper').width();
			var ColWidth = Math.floor(TotalWidth/7);
			var LastColWidth = ColWidth + TotalWidth - 7*ColWidth;
			$('.WeekHeader').width(TotalWidth);
			$('.MonthDayName, .DayColumn').width(ColWidth-1);
			
			
			$('.DayColumn:last, .MonthDayName:last').width(LastColWidth-1);
			$('.CalendarWeekEvent').each(function(){
				Left = (ColWidth - 30) / 4 * Math.min(3, parseInt($(this).attr('LeftPosition')));
				$(this).css('left', Left);
				$(this).width(ColWidth-8-parseInt($(this).css('left')));
			});
			$('.CalendarMonthItem').draggable("option", "grid",[ColWidth, 25] );
			//$('.TodoAgendaLine').draggable("option", "grid",[ColWidth, 25] );
			
			$('.WeekTodoCell').css('height', '');
			var MaxHeight = 0;
			$('.WeekTodoCell').each(function(){
				MaxHeight = Math.max(MaxHeight, parseInt($(this).height()+5));
			});
			$('.WeekTodoCell').height(MaxHeight);
		}
		
		this.PrintEvents = function(Events, Todos, Birthdays){
			var CurrentEvents = new Array();
			var TakenPositions = new Array();
			
			for(i=0; i<Events.length && i<5; i++){
				//Print the event
				this.PrintEvent(Events[i]);
			}
			
			this.PrintTodos(Todos);
		}
		
		this.PrintEvent = function(Event){
			var EventStart = Date.parse(Event['StartDate']);
			var TimeFormat = (CalendarObject.UsesInternationalTimeFormat == 1 ? "HH:mm" : "h:mmt");
			
			if($('#CalendarDay_'+EventStart.toString("yyyy-MM-dd")).find('.CalendarMonthItem').length < 5){
				$('#CalendarDay_'+EventStart.toString("yyyy-MM-dd")).append(
					"<div id='CalendarEvent_"+Event['EventId']+"' class='CalendarEvent CalendarMonthItem CalendarMonthEvent CalendarUserColor_"+Event['UserId']+"' style='' "+
					"EventId='"+Event['EventId']+"' Date='"+EventStart.toString("yyyy-MM-dd")+"' Hour='"+EventStart.toString("HH")+"' Minute='"+EventStart.toString("mm")+"' title='Click to view and edit details'>"+
					"<span style='color:#ddd;text-shadow:none;' class='EventTimeDisplay'>"+EventStart.toString(TimeFormat).toLowerCase()+"</span> "+Event['Name']+""+
					"</div>");
			}
			
		}
			
		this.PrintTodos = function(Todos){
			if(Todos.length > 0){
				for(i=0; i<Todos.length && i<5; i++){
					ThisTodo = Todos[i]
					if($('#CalendarDay_'+ThisTodo['DueDate']).find('.CalendarMonthItem').length < 5){
						$('#CalendarDay_'+ThisTodo['DueDate']).append(
							"<div class='CalendarEvent CalendarMonthTodo CalendarMonthItem CalendarUserColor_"+ThisTodo['UserId']+"' style='' "+ThisTodo['EditAttributes']+" "+
							"ReminderId='"+ThisTodo['ReminderId']+"' Access='"+ThisTodo['Access']+"' Date='"+ThisTodo['DueDate']+"' title='Click to view and edit details'>"+
							"<span style='color:#ddd;text-shadow:none;' class='EventTimeDisplay'>Task:</span> <span "+ThisTodo['ReminderId']+" "+(ThisTodo['IsChecked'] == 1 ? "class='CheckedTodo' style='color:#ccc; text-shadow:none;'" : "")+">"+ThisTodo['Name']+"</span>"+
							"</div>");
					}
				}
				
			}
		}
		
		this.Print = function(){
			var PrintWindow = window.open("/downloads/calendar/print.php?Type=Month","printcal",'width=1000,height=650');
		}
	}
	
	/*******************************************************
						Agenda View
	*******************************************************/
	
	this.AgendaView = function(){		
		this.PrintCalendar = function(){
			//$('#CalendarWrapper').html('');
			
			var FullWidth = 796;
			
			var FullHTML = "<div id='AgendaCalDiv' style='border-bottom:1px solid #ccc; min-height:400px;'></div>";
			
			$('#CalendarWrapper').html(FullHTML);
			
			$('.CalendarRangeIncrement').remove();
			
			$('.DayColumn').bind('click', function(Event){
				EventObject.NewEventDialog($(this).attr('day'))
			});
		}
		
		this.AdjustWidth = function(){}
		
		this.ProcessDays = function(){
			$('.CalendarEvent').remove();

			//var StartDate = Date.parse(CalendarObject.StartDate);
			
			var Today = Date.parse(CalendarObject.StartDate);
			var EndDate = Date.parse(CalendarObject.EndDate);
			var OriginalStartDate = Date.parse(CalendarObject.StartDate);
			
			var AgendaIsEmpty = true;
			var MultipleUsers = $('.SidebarCal_Checkbox:checked').length > 1;
			var HTML = "<table width='100%' cellpadding='0' cellspacing='0'>";
			var CurrentUserId = -1;
			
			//loop through each day on the calendar
			while(Today <= EndDate){
				//Loop through all the events for the current day
				try{
					var TodaysEvents = CalendarObject.Events[Today.toString("yyyy-MM-dd")]['Events'];
					var Todos = CalendarObject.Events[Today.toString("yyyy-MM-dd")]['Todos'];
					var Birthdays = CalendarObject.Events[Today.toString("yyyy-MM-dd")]['Birthdays'];
					var TimeFormat = (CalendarObject.UsesInternationalTimeFormat == 1 ? "HH:mm" : "h:mm tt");
					
					if(TodaysEvents.length > 0 || Todos.length > 0 || Birthdays.length > 0){
						HTML += "<tr><td colspan='99'><div style='font-size:16px; color:#666; font-weight:bold; background-color:#eee; border"+(AgendaIsEmpty ? "-bottom":"")+":1px solid #ccc; border-left:0; border-right:0; padding:8px;"+(AgendaIsEmpty ? "":"margin-top:20px;")+"'>"+Today.toString("dddd, MMMM dS")+"</div></td></tr>";
						AgendaIsEmpty = false;
						
						//print the events
						for(i=0; i < TodaysEvents.length; i++){
							HTML += "<tr><td style='padding-left:20px; color:#999; padding-top:15px; width:130px;' nowrap valign='top' align='right'>"+
									Date.parse(TodaysEvents[i]['StartDate']).toString(TimeFormat).toLowerCase()+" - "+
									Date.parse(TodaysEvents[i]['EndDate']).toString(TimeFormat).toLowerCase()+
									"</td><td valign='top' style='padding-top:15px; padding-left:10px;' >"+
									"<a href='javascript://' onclick='EventObject.EditEventDialog("+TodaysEvents[i]['EventId']+");' class='CalendarUserColorLink_"+TodaysEvents[i]['UserId']+"'>"+TodaysEvents[i]['Name']+"</a>";
							
							HTML += "</td>";
						}
						
						//print the todos
						CurrentUserId = -1;
						for(i=0; i < Todos.length; i++){
							ThisTodo = Todos[i];
							
							if(ThisTodo['Access'] == 'Write'){
								var OnCheck = "ReminderObject.CheckTodo(this);";
								var OnEdit = "ReminderObject.EditReminder(this)";
							}
							else{
								var OnCheck = "DialogAlert(\"You do not have permission to modify this task\")";
								var OnEdit = "DialogAlert(\"You do not have permission to modify this task\")";
							}
							
							HTML += "<tr><td style='padding-left:20px; padding-top:15px; color:#999;' nowrap valign='top' align='right' class='AgendaTaskElementParent'>";
							if(ThisTodo['UserId'] == CurrentUserId){
								//This isn't a new line
								HTML += "</td><td valign='top' style='padding-left:10px;' nowrap> ";
							
							}
							else{
								if(MultipleUsers && ThisTodo['UserId'] != CurrentUserId){
									HTML += "<div class='AgendaTaskElement CalendarUserColorLink_"+ThisTodo['UserId']+"'>"+$('#CalendarUserSName_'+ThisTodo['UserId']).html()+" tasks</div>";
									CurrentUserId = ThisTodo['UserId'];
								}
								else if(ThisTodo['UserId'] != CurrentUserId){
									HTML += "<div class='AgendaTaskElement'>tasks</div>";
									CurrentUserId = ThisTodo['UserId'];
								}
								HTML += "</td><td valign='top' style='padding-top:12px; padding-left:10px;' class='AgendaTaskElementParent' >";
							}
							
							//HTML += "</td><td valign='top' style='padding-top:15px; padding-left:10px;' nowrap>";
							HTML += "<div class='AgendaTaskElement'>"+
								"<a href='javascript://'><img src='/i/app/checkbox"+(ThisTodo['IsChecked'] == 1 ? "_checked" : "")+".png' IsChecked='"+(ThisTodo['IsChecked'] == 1 ? "1" : "0")+"'  onclick='"+OnCheck+"'"+
									"class='Icon TodoIconBig_"+ThisTodo['ReminderId']+" TodoIcon_"+ThisTodo['ReminderId']+"' ReminderId='"+ThisTodo['ReminderId']+"' onmouseover='ReminderObject.HoverDashboardCheckbox(this, "+ThisTodo['ReminderId']+");' onmouseout='ReminderObject.EndHoverDashboardCheckbox(this, "+ThisTodo['ReminderId']+");' /></a>"+
								"<a href='javascript://' onclick='"+OnEdit+"' title='Click to edit this task' "+ThisTodo['EditAttributes']+""+
								"class='NoUnderline TodoLink TodoLink_"+ThisTodo['ReminderId']+" "+(ThisTodo['IsChecked'] == 1 ? "CheckedTodo" : "")+"' style='font-size:line-height:17px;'>"+ThisTodo['Name']+"</a>"+
								(ThisTodo['ContactId'] ? 
									"<div style='font-size:10px;' class='TodoContactInfo TodoContactLinkText_"+ThisTodo['ReminderId']+" "+(ThisTodo['IsChecked'] == 1 ? "GrayedOutTodoContactInfo" : "")+"'>Linked to <a href='/app/View_Contact?ContactId="+ThisTodo['ContactId']+"' class='NoUnderline CalendarTodoContactLink'>"+ThisTodo['ContactName']+"</a></div>"
								 : "")+
								
								"</div>";
							HTML += "</td>";
						}
						
						//Print Birthdays
						if(Birthdays.length > 0){
							HTML += "<tr><td style='padding-left:20px; padding-top:15px; color:#999;' nowrap valign='top' align='right'>";
							HTML += "Birthdays</td><td valign='top' style='padding-top:12px; padding-left:10px;' nowrap>";
							
							
							if(Birthdays.length == 1){
								ThisBirthday = Birthdays[0]
								HTML += "<span class='IconSprite IconSprite-cake'></span> <a href='/app/View_Contact?ContactId="+ThisBirthday['ContactId']+"' class='CalendarTodoContactLink NoUnderline' style='color:#666;'>"+
										ThisBirthday['Salutation']+" "+ThisBirthday['FirstName']+" "+ThisBirthday['MiddleName']+" "+ThisBirthday['LastName']+" "+ThisBirthday['Suffix']+" "+(ThisBirthday['CompanyName'] != 'NULL' ? ThisBirthday['CompanyName'] : "")+" "+"</a>"+
									"";
							}
							else{
								
								HTML += "<span class='IconSprite IconSprite-cake'></span> <a href='javascript://' onclick='CalendarObject.ShowBirthdays(\""+Today.toString("yyyy-MM-dd")+"\");' class='CalendarTodoContactLink NoUnderline' style='color:#666;'>"+
										Birthdays.length+" birthdays"+"</a>"+
									"";
							}
						}
						
					}
				}catch(err){
					//There aren't any events for today
				}
				
				Today = Today.add(1).days();
			}
			
			if(AgendaIsEmpty){
				HTML += "<tr><td align='center' colspan='99' style='padding-top:50px; font-size:16px; font-weight:bold; color:#999;'><div>You don't have anything scheduled for this time period</div></td></tr>";
			}
			
			HTML += "</table><div style=' margin:50px 20px;padding:15px; text-align:center; background-color:#eee; font-size:14px;font-weight:bold; color:#666;'>Showing agenda from "+OriginalStartDate.toString("MMMM dS")+" - "+EndDate.toString("MMMM dS")+". <a href='javascript://' onclick='CalendarObject.ExtendAgendaView();'>Show the next week</a>";
			$('#AgendaCalDiv').html(HTML);
			
			CalendarObject.SetTaskVisibility();
			ProcessSpecificLink('.CalendarTodoContactLink');
		}
		
		this.Print = function(){
			var PrintWindow = window.open("/downloads/calendar/print.php?Type=Agenda","printcal",'width=1000,height=650');
		}
		
	}
	
	
	this.ClearDisplay = function(){
		$('#BodyTop').show();
		$('#BodyMain').show();
		$('#BodyBottom').show();
		$('#CalendarWrapper').hide();
		$('#SidebarBoxWrapper_Calendar').hide();
	}
	
	this.PrintSidebarCalendar = function(BaseDate){
		var Today = BaseDate.moveToFirstDayOfMonth();
		var Month = BaseDate.toString("M");
		this.SidebarCalBaseDate = Date.parse(BaseDate.toString("MM/dd/yyyy"));
		
		var HTML = "<table cellspacing='0' cellpadding='0' align='center'><tr><td colspan='7' align='center'><a href='javascript://' onclick='CalendarObject.SidebarCalNext();' style='float:right;'><img src='/i/app/calendar/sidebar_next.png' /></a><span class='SidebarCal_Month'>"
					+BaseDate.toString('MMMM yyyy')+"</span>"
					+"<a href='javascript://' onclick='CalendarObject.SidebarCalPrevious();' style='float:left;'><img src='/i/app/calendar/sidebar_previous.png' /></a></td></tr>"
					+"</td></tr>";
		
		//scoot back so that the first week starts on sunday
		while(Today.toString('ddd') != "Sun"){
			Today.add(-1).days();
		}
		
		var First = true;
		//loop through the days
		while(Month == Today.toString("M") || Today.toString('ddd') != "Sun" || First){
			if(Today.toString('ddd') == "Sun")
				HTML += "<tr>";
			
			var Classes = "SidebarCal_Day";
			
			if(Today.toString("MM/dd/yyyy") >= this.StartDate && Today.toString("MM/dd/yyyy") <= this.EndDate)
				Classes += " SidebarCal_CurrentDateRange";
			if(Today.toString("MM/dd/yyyy") == Date.today().toString("MM/dd/yyyy"))
				Classes += " SidebarCal_Today";
			if(Today.toString("M") != Month)
				Classes += " SidebarCal_NextMonth";
						
			HTML += "<td class='"+Classes+"' DateString='"+Today.toString("MM/dd/yyyy")+"'>"+Today.toString(" d")+"</td>";
			
			if(Today.toString('ddd') == "Sat")
				HTML += "</tr>";
			
			Today.add(1).days();
			First = false;
		}
		
		HTML += "";
		
		$('#SidebarCalendar').html(HTML);
		
		$('.SidebarCal_Day').bind('click', function(){
			CalendarObject.ChangeDateRange($(this).attr('DateString'));
		});
	}
	
	this.ChangeDateRange = function(NewDate){
		NewDate = Date.parse(NewDate);
		if(this.View == 'Week'){
			while(NewDate.toString('ddd') != "Sun"){
				NewDate.add(-1).days();
			}
			this.StartDate = NewDate.toString("MM/dd/yyyy");
			NewDate.add(1).days();
			
			while(NewDate.toString('ddd') != "Sat"){
				NewDate.add(1).days();
			}
			
			this.EndDate = NewDate.toString("MM/dd/yyyy");
			
			this.Display.PrintCalendar();
			this.GetEvents();
			this.PrintSidebarCalendar(NewDate);
		}
		else if(this.View == 'Day'){
			this.StartDate = NewDate.toString("MM/dd/yyyy");
			this.EndDate = NewDate.toString("MM/dd/yyyy");
			this.Display.PrintCalendar();
			this.GetEvents();
			this.PrintSidebarCalendar(NewDate);
		}
		else if(this.View == 'Agenda'){
			this.StartDate = NewDate.toString("MM/dd/yyyy");
			this.EndDate = NewDate.addDays(6).toString("MM/dd/yyyy");
			this.Display.PrintCalendar();
			this.GetEvents();
			this.PrintSidebarCalendar(NewDate);
		}
		else if(this.View == 'Month'){
			var StartDate = Date.parse(NewDate.toString("yyyy-MM-dd"));
			var EndDate = Date.parse(NewDate.toString("yyyy-MM-dd"));
			
			StartDate.moveToFirstDayOfMonth();
			EndDate.moveToLastDayOfMonth();
			
			this.StartDate = StartDate.toString("MM/dd/yyyy");;
			this.EndDate = EndDate.toString("MM/dd/yyyy");;
			
			this.Display.PrintCalendar();
			this.GetEvents();
			this.PrintSidebarCalendar(NewDate);
		}
	}
	
	this.ExtendAgendaView = function(){
		this.EndDate = Date.parse(this.EndDate).addDays(7).toString("MM/dd/yyyy");
		this.Display.PrintCalendar();
		this.GetEvents();
		this.PrintSidebarCalendar(Date.parse(this.EndDate));
	}
	
	this.PreviousDateRange = function(){
		this.ChangeDateRange(Date.parse(this.StartDate).add(-1).days().toString("MM/dd/yyyy"));
	}
	
	this.NextDateRange = function(){
		this.ChangeDateRange(Date.parse(this.EndDate).add(1).days().toString("MM/dd/yyyy"));
	}
	
	this.SidebarCalPrevious = function(){
		this.PrintSidebarCalendar(this.SidebarCalBaseDate.add(-1).months());
	}
	
	this.SidebarCalNext = function(){
		this.PrintSidebarCalendar(this.SidebarCalBaseDate.add(1).months());
	}
	
	this.ProcessCheckedCalendars = function(){
		$('.SidebarCal_Checkbox').each(function(){
			var UserId = $(this).attr('UserId');
			if($(this).is(':checked')){
				$('#SidebarCal_CheckboxDiv_'+UserId).addClass("SidebarCal_SelectUserDivChecked");
				$('#SidebarCal_CheckboxDiv_'+UserId).addClass("CalendarUserColor_"+UserId);
			}
			else{
				$('#SidebarCal_CheckboxDiv_'+UserId).removeClass("SidebarCal_SelectUserDivChecked");
				$('#SidebarCal_CheckboxDiv_'+UserId).removeClass("CalendarUserColor_"+UserId);
			}
		});
		
	}
}

//There's something weird going on with the arrays for the calendar stuff, so we need to make this size function
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

</SCRIPT>
</DIV>
<DIV id="AJAXPAGE_calendar__css" class="AJAXPageTemplate">
<STYLE>

#CalendarWrapper{
	-webkit-user-select: none;
	-khtml-user-select: none;
	-moz-user-select: none;
	-o-user-select: none;
	user-select: none;
	
	position:relative;
}

.CalendarHeaderRowDiv{
	clear:both;
	overflow:hidden;
	position:relative;
}


.CalendarTodoRowDiv{
	clear:both;
	overflow:hidden;
	font-size:10px;
}

.CalendarEventRowDiv{
	clear:both;
	border-top:1px solid #ccc;
	height:100%;
	overflow:hidden;
	position;relative;
}

.WeekHeader{
	overflow:hidden;
	height:50px;
	text-align:center;
	background-color:#cccccc;
	position:relative;
	border-top:1px solid #ccc;
	border-bottom:1px solid #ccc;
	border-left:1px solid #ccc;
	float:left;
	
	background: #ccc;
	background: -moz-linear-gradient(top, #eeeeee 0%, #cccccc 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fffeeeeee), color-stop(100%,#cccccc));
	background: -webkit-linear-gradient(top, #eeeeee 0%,#cccccc 100%);
	background: -o-linear-gradient(top, #eeeeee 0%,#cccccc 100%);
	background: -ms-linear-gradient(top, #eeeeee 0%,#cccccc 100%);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#eeeeee', endColorstr='#cccccc',GradientType=0 );
	background: linear-gradient(top, #eeeeee 0%,#cccccc 100%);
}

.WeekHeader_Date{
	text-shadow: 1px 1px 0px #fff;
	color:#666666;
	font-size:15px;
	font-weight:bold;
	margin-top:6px;
}

.WeekHeader_Date a{
	text-shadow: 1px 1px 0px #fff;
	color:#666666;
	font-size:15px;
	font-weight:bold;
	margin-top:6px;
	text-decoration:none;
}

.WeekHeader_Date a:hover{
	text-decoration:underline;
	color:#3d6aa6;
}

.WeekHeader_DayName{
	font-size:13px;
	font-weight:bold;
	color:#999999;
	margin-top:2px;
}

.WeekTodoCell{
	min-height:30px;
	background-color:#eeeeee;
	border-bottom:5px solid #cccccc;
	padding-bottom:15px;
	position:relative;
	border-left:1px solid #ccc;
	float:left;
}

.MonthDayName{
	font-size:13px;
	color:#999;
	background-color:#eee;
	border-left:1px solid #ccc;
	font-weight:bold;
	line-height:36px;
	float:left;
}

.DayColumn{
	background-image:url(/i/app/calendar/day_line_back.png);
	height:1200px;
	position:relative;
	float:left;
	border-left:1px solid #cccccc;
}

.DayTimeDisplay{
	position:absolute;
	left:1px;
	font-size:10px;
	background-color:white;
	color:#666666;
	padding:0px 1px;
	z-index:10;
	filter:alpha(opacity=70);
	opacity:0.7;
}

.CalendarWeekEvent{
	position:absolute;
	background-color:#ccc;
	color:white;
	font-size:11px;
	overflow:hidden;
	-webkit-border-radius: 4px;
	-moz-border-radius: 4px;
	border-radius: 4px;
	border-top:1px solid #444;
	border-bottom:1px solid #444;
	padding:0px 3px;
	cursor:default;
	text-shadow: 1px 1px 0px #444;
	box-shadow: 0px 1px 4px #000;
	
	-webkit-user-select: none;
	-khtml-user-select: none;
	-moz-user-select: none;
	-o-user-select: none;
	user-select: none;
}

.CalendarMonthItem{
	font-size:10px;
	text-shadow: 1px 1px 0px #444;
	margin-bottom:1px;
	color:#fff;
	padding:2px 1px;
	height:14px;
	overflow:hidden;
	cursor:default;
	white-space:nowrap;
}

.CalendarAccordion{
	height:40px;
	line-height:40px;
	border-left:1px solid #ccc;
	
	/*background-image:url(/i/app/calendar/accordion.png);*/
}

#CollapsedTimeNotice{
	font-size:11px;
	color:#999999;
	background-color:#eee;
	border:1px solid #999;
	padding:3px 8px;
	-webkit-border-radius: 10px;
	-moz-border-radius: 10px;
	border-radius: 10px;
}

.EventTimeDropdownRow{
	padding:2px;
	cursor:pointer;
	height:16px;
}

.EventTimeDropdownRow:hover{
	background-color:#ccc;
}

.CalendarTodoHeader{
	font-size:11px;
	color:white;
	text-shadow: 1px 1px 0px #444;
	padding:2px 5px;
}

.EventAttachContactDiv{
	position:absolute;
	width:250px;
	padding:5px;
	background-color:#eee;
	border:1px solid #ccc;
	box-shadow: 2px 2px 4px #000;
	z-index:5;
}

.EventAttachContactRow{
	padding:10px;
	cursor:pointer;
}

.EventAttachedContact{
	font-size:11px;
	color:#666;
	
	line-height:17px;
	padding:0px 7px;
	padding-right:25px;
	background-color:#CEEFC0;
	border:1px solid #A9E391;
	-webkit-border-radius: 8px;
	-moz-border-radius: 8px;
	border-radius: 9px;
	float:left;
	margin-bottom:5px;
	position:relative;
	margin-right:5px;
}

.EventAttachedUser{
	font-size:11px;
	color:#666;
	line-height:17px;
	padding:0px 7px;
	padding-right:25px;
	background-color:#C7D6EB;
	border:1px solid #9CB8DC;
	-webkit-border-radius: 8px;
	-moz-border-radius: 8px;
	border-radius: 9px;
	float:left;
	margin-bottom:5px;
	position:relative;
	margin-right:5px;
}

.EventScheduleUser{
	font-size:11px;
	color:#fff;
	line-height:17px;
	padding:0px 7px;
	-webkit-border-radius: 8px;
	-moz-border-radius: 8px;
	border-radius: 9px;
	float:left;
	margin-bottom:5px;
	position:relative;
	margin-right:5px;
}

.EventAttachedLink{
	text-decoration:none;
	color:#666;
}

.EventAttachedLink:hover{
	text-decoration:underline;
	color:#3d6aa6;
}

/*Sidebar stuff*/

.CalendarSidebarHeader{
	overflow:hidden;
	border-bottom:1px solid #ccc;
}

.CalendarSidebarViewSelect{
	height:31px;
	line-height:31px;
	text-align:center;
	color:#999999;
	font-size:13px;
	overflow:hidden;
	position:relative;
	cursor:pointer;
	padding:0px 10px;
	
	background: #f5f5f5;
	background: -moz-linear-gradient(top, #f5f5f5 0%, #dddddd 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f5f5f5), color-stop(100%,#dddddd));
	background: -webkit-linear-gradient(top, #f5f5f5 0%,#dddddd 100%);
	background: -o-linear-gradient(top, #f5f5f5 0%,#dddddd 100%);
	background: -ms-linear-gradient(top, #f5f5f5 0%,#dddddd 100%);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f5f5f5', endColorstr='#dddddd',GradientType=0 );
	background: linear-gradient(top, #f5f5f5 0%,#dddddd 100%);
}

.CalendarSidebarViewSelect:hover{
	background: #cccccc;
	background: -moz-linear-gradient(top, #cccccc 0%, #dddddd 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#cccccc), color-stop(100%,#dddddd));
	background: -webkit-linear-gradient(top, #cccccc 0%,#dddddd 100%);
	background: -o-linear-gradient(top, #cccccc 0%,#dddddd 100%);
	background: -ms-linear-gradient(top, #cccccc 0%,#dddddd 100%);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#cccccc', endColorstr='#dddddd',GradientType=0 );
	background: linear-gradient(top, #cccccc 0%,#dddddd 100%);
}

.CalendarViewHighlighted{
	text-shadow: #000 1px 1px 0px;
	font-weight:bold;
	color:#fff;
	border-left:1px solid #bbb;
	background: #cccccc;
	background: -moz-linear-gradient(top, #cccccc 0%, #999999 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#cccccc), color-stop(100%,#999999));
	background: -webkit-linear-gradient(top, #cccccc 0%,#999999 100%);
	background: -o-linear-gradient(top, #cccccc 0%,#999999 100%);
	background: -ms-linear-gradient(top, #cccccc 0%,#999999 100%);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#cccccc', endColorstr='#999999',GradientType=0 );
	background: linear-gradient(top, #cccccc 0%,#999999 100%);
}

.SidebarCal_CurrentDateRange{
	background-color:#CDDAED;
}

.SidebarCal_Month{
	font-weight:bold;
	color:#666;
	font-size:11px;
	height:19px;
}

.SidebarCal_Day{
	font-weight:bold;
	color:#666;
	font-size:11px;
	width:25px;
	text-align:center;
	cursor:pointer;
	padding:1px;
	height:19px;
}

.SidebarCal_Today{
	border:1px solid #999;
	padding:0px;
}

.SidebarCal_NextMonth{
	font-weight:normal;
	color:#aaa;
}

.SidebarCal_SelectUserDiv{
	margin:3px;
}

.SidebarCal_SelectUserDivChecked{
	color:white;
}

/* End Sidebar stuff*/


.CalendarUserColor_39944{
	background-color:#3D6AA6;
}

.CalendarUserColorLink_39944{
	color:#3D6AA6;
	font-weight:bold;
}


</STYLE>
</DIV>
<DIV id="AJAXPAGE_dashboard" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Workspace - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = false;
	TempPageSettings['JSBeforeAJAX'] = 'RedirectToWorkspace()';
	
	PageSettings["dashboard"] = TempPageSettings;
	
	</SCRIPT>

<SCRIPT type="text/javascript">

function RedirectToWorkspace(){
	jQuery.history.load('/app/Workspace');
}

</SCRIPT>
</DIV>
<DIV id="AJAXPAGE_view_contact" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'View Contact - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = 'ViewContactObject.Reset();LogAnalyticsModule("CRM");';
	
	PageSettings["view_contact"] = TempPageSettings;
	
	</SCRIPT>

<STYLE>



.ContactDetailsFieldName{
	font-size:11px;
	color:#999999;
}

.ContactDetailsInfo{
	font-size:12px;
}

.ContactDetailsInfo a{
	color:#333333;
	text-decoration:none;
}

.ContactDetailsInfo a:hover{
	text-decoration:underline;
}

.ContactDetailsLineSpacing{
	height:8px;
	overflow:hidden;
}

.ContactDetailsFieldType{
	font-size:10px;
	color:#999999;
}

.ContactOptionsDropdownButton{
	padding:0px 7px;
	height:24px;
	line-height:24px;
	background-color:#eeeeee;
	border:1px solid #cccccc;
	cursor:pointer;
	color:#3d6aa6;
	font-weight:bold;
	width:100px;
	
	-webkit-border-radius: 4px;
	-moz-border-radius: 4px;
	border-radius: 4px;		
}

.ContactOptionsDropdownButtonHighlighted{
	background-color:#dddddd;
}

.ContactOptionsDropdown{
	position:absolute;
	background-color:#eeeeee;
	border:1px solid #cccccc;
	width:250px;
	right:0px;
	z-index:999;
	-moz-box-shadow: 7px 3px 3px #888;
	-webkit-box-shadow: 3px 3px 5px #888;
	box-shadow: 7px 3px 3px #888;
}

.ContactOptionsDropdown .OptionRow{
	line-height:30px;
	margin:0px 5px;
}

.ContactOptionsDropdown .OptionRow a {
	color:#888888;
	text-decoration:none;
	font-weight:bold;
}

.ContactOptionsDropdown .OptionRow a:hover {
	text-decoration:underline;
}

.ContactEventAssignee{
	font-size:10px;
	color:white;
	padding:2px;
	margin-left:10px;
}

.ViewContact_AssignedTo{
	background-color:#bbb;
}

.EnterNoteDiv{
	background-color:#f5f5f5;
	border:1px solid #ddd;
	margin: 20px 15px;
	padding:5px;
	border-radius:4px;
}

.ContactNoteField{
	border:1px solid #ddd;
	border-radius:6px;
	width:98%;
	height:40px;
	padding:6px;
	margin:0px;
	overflow:visible;
}


/*****************************************************
************ History CSS
****************************************************/

.HistoryDateHeader{
	background-color:#f5f5f5;
	color:#999;
	border-bottom:1px solid #ddd;
	font-weight:bold;
	font-size:14px;
	padding:4px;
	padding-left:10px;
	
}

.HistoryItem{
	clear:both;
	padding:9px 10px;
	padding-bottom:7px;
	position:relative;
	border-bottom:1px solid #ddd;
}

.HistoryItemBottomBorder{
	border-bottom:1px solid #dddddd;
}

.HistoryCompanyName{
	font-size:12px;
	color:#999;
	font-weight:normal;
	padding-left:10px;
}

.HistoryCompanyName a{
	color:#999;
	text-decoration:none;
}
.HistoryCompanyName a:hover{
	text-decoration:underline;
}


.HistoryDescription{
	padding-left:25px;
	background-repeat:no-repeat;
	position:relative;
}

.HistoryMainDescription{
	padding-right:10px;
}

.HistoryTime{
	color:#aaaaaa;
	font-style:italic;
	font-size:10px;
	white-space:nowrap;
}

.HistoryEdit{
	font-size:11px;
	padding-left:25px;
	padding-top:5px;
	height:15px;
}

.HistoryEdit a{
	display:none;
}

.DeleteNoteConfirmation{
	position:absolute;
	background-color:#fff;
	top:0px;
	left:0px;
	padding:10px;
	padding-top:20px;
	font-weight:bold;
	color:#666;
	
	 -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=75)";
     filter: alpha(opacity=75);
     -moz-opacity:0.75;
	 -khtml-opacity: 0.75;
     opacity: 0.75;
}


/*****************************************************
************ END History CSS
****************************************************/

.ContactSummaryLine{
	padding:15px;
	border-bottom:1px solid #ddd;
	color:#999;
	font-size:13px;
	clear:both;
}

.GroupTag{
	padding:3px 8px;
	padding-top:1px;
	border:1px solid #cccccc;
	margin-left:7px;
	margin-bottom:5px;
	position:relative;
	background-color:#eeeeee;
	position:relative;
	border-radius:5px;
	float:left;
	overflow:hidden;
}

.GroupTag a{
	color:#666;
	font-size:12px;
	text-decoration:none;
}

.GroupTagHover{
	background: #c5c5c5;
	background: -moz-linear-gradient(top, #c5c5c5 0%, #aaaaaa 99%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#c5c5c5), color-stop(99%,#aaaaaa));
	background: -webkit-linear-gradient(top, #c5c5c5 0%,#aaaaaa 99%);
	background: -o-linear-gradient(top, #c5c5c5 0%,#aaaaaa 99%);
	background: -ms-linear-gradient(top, #c5c5c5 0%,#aaaaaa 99%);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#c5c5c5', endColorstr='#aaaaaa',GradientType=0 );
	background: linear-gradient(top, #c5c5c5 0%,#aaaaaa 99%);
	color:#fff;
	text-shadow:none;
	border-radius:5px;
}

.GroupTagHover a{
	color:#fff;
}

.PipelineBadgeDiv{
	width:315px;
	border:1px solid #ddd;
	background-color:#eee;
	float:left;
	margin-right:15px;
	margin-top:10px;
	color:#666;
	border-radius:5px;
}


</STYLE>

<DIV id="FrameworkViewContactDiv"></DIV>
<SCRIPT type="text/javascript">

var ViewContactObject = new ViewContactClass();

function ViewContactClass(){
	this.DefaultNoteText = "Enter a note";
	this.ContactId = "";
	this.SelectedDate;
	this.CurrentContactInfo = "";
	this.EditNoteId;
	
	this.Reset = function(){
		SetBodyColumn(280);
		ResizeEvent = "ViewContactObject.AdjustWidth()";
		$('#FrameworkViewContactDiv').html('');
		
		CloseDialogFromSource("NewEvent"); //in case we came from the calendar
		
		//Handle the contact list on the sidebar
		this.ContactId = CurrentPageParams['ContactId'];
		PermSidebarObject.SelectContactOnSidebar();
	}
	
	this.AdjustWidth = function(){
		$('.ViewContactMainPane').css('width', $('#BodyMain').width() - $('.ViewContactLeftPane').width()+'px');
	}
	
	this.Init = function(){
		ResizeWindow();
		this.SelectedDate = ReminderObject.Tomorrow;
		
		this.DefaultNoteText = "Enter a note about "+this.CurrentContactInfo['ShortName'];
		AddTextAreaDefault("#Note", this.DefaultNoteText, "#bbbbbb");
		
		$('.ContactOptionsDropdownButton').bind('mouseover', function(){
			$(this).addClass('ContactOptionsDropdownButtonHighlighted');
		});
		$('.ContactOptionsDropdownButton').bind('mouseout', function(){
			$('.ContactOptionsDropdownButton').removeClass('ContactOptionsDropdownButtonHighlighted');
		});
		$('.ContactOptionsDropdownButton').bind('click', function(){
			$('.ContactOptionsDropdown').slideDown('fast');
		});
		
		this.RefreshGroupMouseovers();
		
		this.ShowCompanyNotes();
		$('#ShowContactHistoriesToo').bind('click', function(){
			ViewContactObject.ShowCompanyNotes();
		});
		
		RedCross = new Image(); 
		RedCross.src = "/i/app/remove_from_group_red.png";
		
		this.CheckHubspotInfo();
	}
	
	this.DeleteContact = function(){
		Dialog("<div align='center' class='DeleteContactDialog' style='padding:20px;'><div style='font-size:16px; font-weight:bold; color:#999999;'>Are you sure you want to delete this contact?</div><br /><strong><a href='javascript://' onclick='ViewContactObject.ConfirmDeleteContact();'>Yes, delete</a></strong> <span style='padding:15px;'></span><a href='javascript://' onclick='CloseDialog($(this));' style='color:#999999;'>Cancel</a>");
	}
	
	this.ShowCompanyNotes = function(){
		if($('#ShowContactHistoriesToo:checked').val() !== undefined){
			$('#EntireCompanyHistory').show();
			$('#ContactOnlyHistory').hide();
		}
		else{
			$('#EntireCompanyHistory').hide();
			$('#ContactOnlyHistory').show();
		}
	}
	
	this.ConfirmDeleteContact = function(){
		$('.DeleteContactDialog').html("<img src='style/default/images/main/loading.gif' />");
		$.post('/appinclude/action/view_contact/delete_contact.php', {ContactId:this.ContactId}, function(data){
			CloseDialog('.DeleteContactDialog');
			SystemMessage("The contact has been deleted");
			PermSidebarObject.RemoveContactFromSidebar(ViewContactObject.ContactId);
			jQuery.history.load('/app/View_Contact?ContactId='+ViewContactObject.ContactId+"&Delete=true");
		});
	}
	
	this.SetSpecificDate = function(datetext, inst){
		this.SelectedDate = datetext;
		
		if(ReminderObject.Today >= datetext){
			$('#NoteReminderDateWarning').fadeIn('slow');
		}
		else
			$('#NoteReminderDateWarning').hide();
		
		/*
		$('.DisplayDateSummary').html($.datepicker.formatDate('DD, MM d', new Date(datetext)));
		$('.DisplayActualDate').html('');
		$('.DateDropdown').hide();*/
	}
	
	this.SaveNote = function(){
		ThisNote = $('#Note').val();
		
		if(ThisNote == this.DefaultNoteText || ThisNote == ''){
			DialogAlert("Please type a note before saving.");
			return;
		}
		
		GrayOutArea('.GrayOutContactNoteDiv', true);
		$.post("/appinclude/action/view_contact/save_note.php", {ContactId:this.ContactId, Note:ThisNote }, function(Data){
			ViewContactObject.UpdatePageAfterSave(Data);
			$('.ContactNoteField').animate({
				height:'40'
			});
		});
		
	}
	
	this.SaveNoteAndReminder = function(){
		this.SaveNote(true);
	}
	
	this.ShowReminder = function(){
		
		$('.NoteReminderDatePicker').datepicker({
			inline: true,
			numberOfMonths:1,
			onSelect:function(datetext, inst){
				ViewContactObject.SetSpecificDate(datetext, inst);
			}
		});
		
		this.SelectedDate = ReminderObject.Tomorrow;
		$('.NoteReminderDatePicker').datepicker('setDate', new Date(ReminderObject.Tomorrow));
		$('#NoteReminderDateWarning').hide();
		
		$('#NoteSaveBasicDiv').hide();
		$('#NoteReminderDiv').slideDown('fast');
		
		/*
		$('#NoteBasicDiv').slideUp('fast'), function(){
			$('#NoteReminderDiv').slideDown('fast');
		}*/
	}
	
	this.CancelReminder = function(){
		$('#NoteReminderDiv').slideUp('fast', function(){
			$('#NoteSaveBasicDiv').slideDown('fast');
		});
	}
	
	this.UpdatePageAfterSave = function(Data){
		EndGrayOutArea();
		this.CancelReminder();
		ThisNote = $('#Note').val(this.DefaultNoteText);
		$('#HistoryBlankSlate').remove();
		InsertMarkupFromAJAX(Data);
		
		this.ShowCompanyNotes();
		
		AddTextAreaDefault("#Note", this.DefaultNoteText, "#bbbbbb");
	}
	
	this.ViewFullEmail = function(NoteId){
		Dialog("<iframe src='/appinclude/action/view_contact/view_email.php?NoteId="+NoteId+"' style='height:500px; width:800px; border:0;'>You can't view this email because your browser doesn't support iframes.</iframe>", 800);
	}
	
	this.ViewMailChimpEmail = function(ThisActivityId){
		var DialogId = Dialog("<div class='MailChimpDialogView' style='height:500px;'></div>", 850);
		GrayOutArea('.MailChimpDialogView', true);
		
		$.post('/appinclude/action/view_contact/view_mailchimp_email.php', {ActivityId:ThisActivityId}, function(Data){
			InsertMarkupFromAJAX(Data);
			RepositionDialogs();
			ProcessLinks('.MailChimpDialogView');
		});
	}
	
	this.ShowEditOptions = function(NoteId){
		$(".HistoryEdit_"+NoteId+" a").show();
	}
	
	this.HideEditOptions = function(NoteId){
		$(".HistoryEdit_"+NoteId+" a").hide();
	}
	
	this.DeleteNote = function(ThisNoteId){
		NoteId = ThisNoteId;
		//It's possible for more than one feed to be loaded at a time, so we need to loop through of them
		$('.NoteItemWrapper_'+NoteId).each(function(){
			$(this).append("<div class='DeleteNoteConfirmation DeleteNoteConfirmation_"+NoteId+"' align='center'><span class='IconSprite IconSprite-bin'></span> This item has been deleted. <a href='javascript://' onclick='ViewContactObject.UndoDelete("+NoteId+")'>Undo</a></div>");
			$(this).find('.DeleteNoteConfirmation_'+NoteId).height($(this).height()-14);
			$(this).find('.DeleteNoteConfirmation_'+NoteId).width($(this).width());
			$(this).attr('IsDeleted', 'TRUE');
		});
		
		
		$.post('/appinclude/action/view_contact/delete_note.php', {NoteId:ThisNoteId}, function(data){
			InsertMarkupFromAJAX(data);
		});
	}
	
	this.UndoDelete = function(ThisNoteId){
		NoteId = ThisNoteId;
		$('.NoteItemWrapper_'+NoteId).attr('IsDeleted', 'FALSE');
		$('.DeleteNoteConfirmation_'+NoteId).remove();
		
		$.post('/appinclude/action/view_contact/delete_note.php', {NoteId:ThisNoteId, UndoDelete:'true'}, function(data){
			InsertMarkupFromAJAX(data);
		});
	}
	
	this.EditNoteDialog = function(ThisNoteId){
		DialogId = Dialog("<div id='EditNoteDialogWrapper'><div class='DialogHeader'>Edit Note</div><div id='EditNoteDialog' style='padding:20px;'><br /><br /><br /><br /><div align='center'><img src='style/default/images/main/loading.gif' /></div><br /><br /><br /><br /></div></div>", 550, "ViewContactObject.CloseEditDialog();");
		$.post('/appinclude/action/view_contact/get_note_to_edit.php', {NoteId:ThisNoteId}, function(Data){
			InsertMarkupFromAJAX(Data);
		});
	}
	
	this.CloseEditDialog = function(){
		$('#EditNoteDiv').appendTo("#EditNoteWrapper");
		CloseDialog('#EditNoteDialog');
	}
	
	this.ShowStatusDiv = function(){
		var PipelineId = $('#EditNotePipelineId').val();
		$('.EditNoteStatus').hide();
		if(PipelineId == 'Note' || PipelineId == null){
			$('#EditNotePipelineDetails').hide();
		}
		else{
			$('#EditNotePipelineDetails').show();
			$('#EditNoteStatus_'+PipelineId).show();
		}
	}
	
	this.SaveEditNote = function(ThisNoteId){
		GrayOutArea("#EditNoteDialogWrapper", true);
		$.post("/appinclude/action/view_contact/edit_note.php", {NoteId:ThisNoteId, Note:$('#EditNoteTextField').val()}, function(Data){
			CloseDialogs();
			InsertMarkupFromAJAX(Data);
		});
	}
	
	this.ShowGroupDialog = function(){
		AddGroupObject = this;
		GroupObject.AddContactToGroup("Add "+this.CurrentContactInfo['ShortName']+" to a group");
	}
	
	this.AddContactToGroup = function(ThisGroupId){
		GrayOutArea('#AddContactToGroup', true);
		$.post('/appinclude/action/groups/add_contact_to_group.php', {ContactId:this.ContactId, GroupId:ThisGroupId}, function(Data){
			InsertMarkupFromAJAX(Data);
			Pulse('#ViewContactGroups');
			EndGrayOutArea();
			CloseDialog($('#AddContactToGroup').parent());
			ViewContactObject.RefreshGroupMouseovers();
		});
	}
	
	this.CreateGroupAndAddContact = function(){
		if($('#AddContactToGroup #AddToGroupNewGroupName').val() == '' || $('#AddContactToGroup #AddToGroupNewGroupName').val() == "Enter group name"){
			$('#AddContactToGroup .GroupNameWarning').fadeIn("fast");
			return;
		}
		
		$('#AddContactToGroup .GroupNameWarning').hide();
		$('#AddContactToGroup .GroupNameTaken').hide();
		
		GrayOutArea('#AddContactToGroup', true);
		
		$.post('/appinclude/action/groups/add_contact_to_new_group.php', {ContactId:this.ContactId, GroupName:$('#AddContactToGroup #AddToGroupNewGroupName').val()},
		function(data){
			EndGrayOutArea();
			InsertMarkupFromAJAX(data);
			ViewContactObject.RefreshGroupMouseovers();
			Pulse('#ViewContactGroups');
		});
	}
	
	this.RemoveFromGroup = function(Element){
		$(Element).parent().hide('slow');
	
		ThisGroupId = $(Element).attr('GroupId');
		$.post('/appinclude/action/groups/remove_contact_from_group.php', {ContactId:this.ContactId, GroupId:ThisGroupId}, function(data){
			InsertMarkupFromAJAX(data);
		});
	}
	
	this.RefreshGroupMouseovers = function(){
		$('.GoToGroup').mouseenter(function(){
			$(this).parent().addClass("GroupTagHover");
		});
		$('.GoToGroup').mouseleave(function(){
			$(this).parent().removeClass("GroupTagHover");
		});
	}
	
	this.AssignOwnerDialog = function(){
		Dialog("<div id='AssignOwnerDialog'>"+$('#AssignOwnerDiv').html()+"</div>", 350);
	}
	
	this.AssignOwner = function(ThisUserId){
		GrayOutArea('#AssignOwnerDialog', true);
		$.post('/appinclude/action/view_contact/assign_to_user.php', {ContactId:this.ContactId, NewUserId:ThisUserId}, function(Data){
			InsertMarkupFromAJAX(Data);
			CloseDialog('#AssignOwnerDialog');

			SystemMessage(ViewContactObject.CurrentContactInfo['FullName']+" has been assigned to "+$('#AssignOwner_'+ThisUserId).html());
		});
	}
	
	this.ExpandNoteField = function(){
		if($('.ContactNoteField').height() < 100){
			$('.ContactNoteField').animate({
					height:'100'
			});
		}
	}
	this.MinimizeNoteField = function(){
		if($('.ContactNoteField').height() <= 100 && (this.DefaultNoteText == $('.ContactNoteField').val() || $('.ContactNoteField').val() == '')){
			$('.ContactNoteField').animate({
					height:'40'
			});
		}
	}
	
	this.ShowAllContactActivity = function(Element){
		GrayOutArea('#History', true);
		$.post("/appinclude/action/view_contact/show_all_contact_activity.php", 
				{ShowAllContactActivity:($(Element).attr('checked') ? 1 : 0), ContactId:this.ContactId}, function(Data){
			//Dialog(Data);
			InsertMarkupFromAJAX(Data);
		});
	}
	
	this.Print = function(){
		var PrintWindow = window.open("/downloads/contact/print.php","printcal",'width=1000,height=650');
	}
	
	this.CheckHubspotInfo = function(){
		if($('#HubspotLoadingSection').length > 0){
			this.LoadHubspotInfo();
		}
		else{
			//there's nothing to do because the info is already up to date
		}
	}
	
	this.LoadHubspotInfo = function(){
		$('#HubspotInfo').html("loading...");
		$.post("/appinclude/action/view_contact/hubspot_info.php", {ContactId:this.ContactId}, function(Data){
			InsertMarkupFromAJAX(Data);
		});
	}
}

</SCRIPT>
</DIV>
<DIV id="AJAXPAGE_js__event" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">

var EventObject = new EventClass();

$(function(){
	//EventObject.NewEventDialog();
	
	$('#EventDialog_StartTime, #EventDialog_EndTime').bind('focus', function(){		
		$('.EventTimeDropdownDiv').remove();
		
		if($(this).attr('id') == 'EventDialog_StartTime')
			var FieldType = 'Start';
		else
			var FieldType = 'End';
		
		var DropdownSource = "<div class='EventTimeDropdownDiv' style='position:absolute; width:90px; font-size:12px; background-color:#fff; border:1px solid #999;padding:5px; height:200px; overflow:auto;'>";
		var ModCount = 0;
		for(i=0; i<24; i++){
			ModCount = i%12;
			if(ModCount == 0)
				ModCount = 12;
			
			if(false){
				DropdownSource += "<div class='EventTimeDropdownRow'>"+(i < 10 ? "0" : "")+""+i+":00</div>";
				DropdownSource += "<div class='EventTimeDropdownRow'>"+(i < 10 ? "0" : "")+""+i+":30</div>";
			}
			else{
				DropdownSource += "<div class='EventTimeDropdownRow'>"+ModCount+":00 "+(i>=12 ? "pm" : "am")+"</div>";
				DropdownSource += "<div class='EventTimeDropdownRow'>"+ModCount+":30 "+(i>=12 ? "pm" : "am")+"</div>";
			}
		}
		DropdownSource += "</div>";
		
		$(this).after(DropdownSource);
		
		var LeftPosition = $(this).position().left;
		$('.EventTimeDropdownDiv').css('left', LeftPosition+'px');
		
		//Scroll the time dropdowns to the right place
		try{$('.EventTimeDropdownDiv').scrollTop(parseInt(Date.parse($(this).val()).toString('H'))*40);}catch(err){}
		
		$('.EventTimeDropdownRow').bind('click', function(){
			//Set the end time automatically
			if(FieldType == 'Start'){
				EventObject.AutosetEndTime($('#EventDialog_StartTime').val(), $(this).html());
				EventObject.CurrentStartTime = $(this).html();
			}
			
			$('#EventDialog_'+FieldType+'Time').val($(this).html());
			$('.EventTimeDropdownDiv').remove();
			$('#EventDialog_'+FieldType+'Time, #EventDialog_EndTime').blur();
		});
		
		
		ShowDropdown(".EventTimeDropdownDiv", "#EventDialog_StartTime, #EventDialog_EndTime", "EventObject.RemoveTimeDropdown()");
	});
	
	$('#EventDialog_StartTime').bind('change', function(){
		EventObject.AutosetEndTime(EventObject.CurrentStartTime , $('#EventDialog_StartTime').val());
		EventObject.CurrentStartTime = $('#EventDialog_StartTime').val();
	});
	
	
	$('#EventDialog_Name').bind('keydown', 'return', function(){
		EventObject.SaveEvent();
	});
});

function EventClass(){
	this.DefaultReminders = eval('('+ '[{"Type":"Email","Value":"15","Unit":"Minutes"}]' + ')');
	this.HasSMS = false;
	this.ReminderCount = 0;
	this.HasSharingUsers = false;
	this.AttachedUsers = new Array();
	this.AttachedContacts = new Array();
	this.CurrentStartTime = '';
	this.EditEventId = 0;
	
	this.NewEventDialog = function(DefaultDate, StartTime){
		this.EditEventId = 0;
		
		$('.EventDialog_New').show();
		$('.EventDialog_Edit').hide();
		$('#EventDialogReadDiv').hide();
		$('#EventDialogWriteDiv').show();
		$('#EventDialog_ReminderSection').show();
		
		if(DefaultDate == null)
			DefaultDate = Date.today();
		else
			DefaultDate = Date.parse(DefaultDate);
		
		DialogFromSource("NewEvent", 810);
		this.AttachedUsers = new Array();
		this.AttachedUsers.push("39944");
		this.AttachedContacts = new Array();
		
		$('#EventDialog_Name').val('');
		$('#EventDialog_Description').val('');
		
		this.Init();
		$('#EventDialog_DatePicker').datepicker("setDate", DefaultDate);
		
		$('#EventDialog_Name').focus();
		
		//Create the reminders
		$('#EventDialog_ReminderSource').html("");
		for(i=0; i<this.DefaultReminders.length; i++){
			var Reminder = this.DefaultReminders[i];
			this.AddReminder(Reminder['Type'], Reminder['Value'], Reminder['Unit']);
		}
		
		if(StartTime != null){
			//var StartTime = Date.parse(StartTime).add(1).hours().toString('h')+":00 "+Date.parse('now').add(1).hours().toString('tt').toLowerCase();
			var EndTime = Date.parse(StartTime).add(1).hours().toString('h')+":"+Date.parse(StartTime).add(1).hours().toString('mm')+" "+Date.parse(StartTime).add(1).hours().toString('tt').toLowerCase();
		}
		else{
			var StartTime = Date.parse('now').add(1).hours().toString('h')+":00 "+Date.parse('now').add(1).hours().toString('tt').toLowerCase();
			var EndTime = Date.parse('now').add(2).hours().toString('h')+":00 "+Date.parse('now').add(2).hours().toString('tt').toLowerCase();
		}
		
		//don't allow events to start after 11 pm
		if(parseInt(Date.parse(StartTime).toString('H')) > 21){
			var StartTime = '10:00 pm';
			var EndTime = '11:00 pm';
		}
		
		
		//set up the links on the right side
		this.DrawAttachedContacts();
		this.DrawAttachedUsers();
		
		if(false){
			StartTime = Date.parse(StartTime).toString("HH:mm");
			EndTime = Date.parse(EndTime).toString("HH:mm");
		}
		
		this.CurrentStartTime = StartTime;
		$('#EventDialog_StartTime').val(StartTime);
		$('#EventDialog_EndTime').val(EndTime);
		
		//setTimeout("EventObject.LoadSchedule();", 5000);
	}
	
	this.EditEventDialog = function(ThisEventId){
		this.NewEventDialog();
		$('.EventDialog_New').hide();
		$('.EventDialog_Edit').show();
		GrayOutArea('#DialogDiv', true);
		
		this.EditEventId = ThisEventId
		
		$.post('/appinclude/action/calendar/get_edit_event_info.php', {EventId:ThisEventId}, function(Data){
			InsertMarkupFromAJAX(Data)
		});
	}
	
	this.PopulateEditEventDialog = function(Data){
		var EventInfo = eval('(' + Data + ')');
		
		//Event Info
		$('#EventDialog_Name').val(EventInfo['Event']['Name']);
		$('#EventDialog_Description').val(EventInfo['Event']['Description']);
		$('#EventDialog_DatePicker').datepicker("setDate", Date.parse(EventInfo['Event']['StartDate']));
		if(false){
			$('#EventDialog_StartTime').val(Date.parse(EventInfo['Event']['StartDate']).toString("HH:mm").toLowerCase());
			$('#EventDialog_EndTime').val(Date.parse(EventInfo['Event']['EndDate']).toString("HH:mm").toLowerCase());
		}
		else{
			$('#EventDialog_StartTime').val(Date.parse(EventInfo['Event']['StartDate']).toString("h:mm tt").toLowerCase());
			$('#EventDialog_EndTime').val(Date.parse(EventInfo['Event']['EndDate']).toString("h:mm tt").toLowerCase());
		}
		
		this.CurrentStartTime = Date.parse(EventInfo['Event']['StartDate']);
		
		
		//Users
		this.AttachedUsers = new Array();
		$.each(EventInfo['Users'], function(Index, Value){
			EventObject.AttachedUsers.push(Value['UserId']);
		});
		
		this.AttachedContacts = EventInfo['Contacts'];
		
		this.DrawAttachedContacts();
		this.DrawAttachedUsers();
		
		//Reminders - if the user isn't scheduled to attend, use the default reminders in case they're added
		$('#EventDialog_ReminderSource').html("");
		if(!this.UserIsAttending()){
			for(i=0; i<this.DefaultReminders.length; i++){
				var Reminder = this.DefaultReminders[i];
				this.AddReminder(Reminder['Type'], Reminder['Value'], Reminder['Unit']);
			}
		}
		else{
			$.each(EventInfo['Reminders'], function(Index, Value){
				EventObject.AddReminder(Value['Type'], Value['Value'], Value['Unit']);
			});
		}
	
		EndGrayOutArea();
	}
	
	//This is either called from NewEventDialog or EditEventDialog
	this.Init = function(){
		$('#EventDialog_DatePicker').datepicker({
			changeMonth: true,
			changeYear: true,
			onSelect: function(dateText, inst){EventObject.LoadSchedule()}
		});
		
		this.ReminderCount = 0;
	}
	
	//If the start time changes, we should auto-change the end time
	this.AutosetEndTime = function(OldStartTime, NewStartTime){
		try{
			var TimeDiff = Date.parse($('#EventDialog_EndTime').val()).getTime() - Date.parse(OldStartTime).getTime();
			if(false){
				var NewTime = Date.parse(NewStartTime).add(TimeDiff).milliseconds().toString("HH:mm").toLowerCase();
			}
			else{
				var NewTime = Date.parse(NewStartTime).add(TimeDiff).milliseconds().toString("h:mm tt").toLowerCase();
			}
			$('#EventDialog_EndTime').val(NewTime);
		}catch(err){}
	}
	
	this.AddReminder = function(Type, Value, Unit){
		if(Type == null)
			Type = "Email";
		if(Value == null)
			Value = "15";
		if(Unit == null)
			Unit = "Minutes";
		
		this.ReminderCount++;
		var i = this.ReminderCount;
		
		var ReminderSrc = "<div style='margin:5px 0px;' id='EventReminder_"+i+"'>";
		ReminderSrc += "<select id='ReminderType_"+i+"' name='Reminders["+i+"][Type]' style='width:70px;'><option value='Email'>Email</option><option value='SMS'>SMS</option></select><span style='padding:5px;'></span>";
		ReminderSrc += "<input type='text' name='Reminders["+i+"][Value]' id='ReminderValue_"+i+"' style='width:30px;' /><span style='padding:5px;'></span>";
		ReminderSrc += "<select id='ReminderUnit_"+i+"' name='Reminders["+i+"][Unit]' ><option value='Minutes'>minutes</option><option value='Hours'>hours</option><option value='Days'>days</option></select><span style='padding:5px;'></span>before the event starts<span style='padding:5px;'></span>";
		ReminderSrc += "<a href='javascript://' onclick='EventObject.DeleteReminder("+i+");'><img src='/i/app/calendar/remove_reminder.png' title='Delete this reminder' /></a>";
		ReminderSrc += "</div>";
		$('#EventDialog_ReminderSource').append(ReminderSrc);
		
		//capitalize the first letter of the unit just in case
		Unit = Unit.charAt(0).toUpperCase() + Unit.slice(1);
		
		$("#ReminderType_"+i).val(Type);
		$("#ReminderValue_"+i).val(Value);
		$("#ReminderUnit_"+i).val(Unit);
		
		$("#ReminderType_"+i).bind('change', function(){
			if($(this).val() == 'SMS' && !EventObject.HasSMS){
				alert("You need to set up SMS reminders. To do this, click the \"Settings\" link at the top of the page and go to your calendar settings.");
				$(this).val("Email");
			}
		});
	}
	
	this.DrawAttachedContacts = function(){
		$('.EventFormAttachedContact').remove();
		
		if(this.AttachedContacts.length == 0){
			$('#EventDialog_Contacts').html("<a href='javascript://' class='EventAttachedContactLink ShowAttachContactMenu IconSprite IconSprite-add_translucent' ></a>"+
				" <a href='javascript://' class='EventAttachedContactLink ShowAttachContactMenu' style='font-size:11px;'>Attach a contact</a>");
		}
		else{
			var HTML = "";
			
			HTML += ""+
				"<div style='padding:5px; background-color:#eee;'>"+
				"<div class='BoldGray' align='center' style='margin-bottom:10px;'>Attached Contacts</div>";
			
			$.each(this.AttachedContacts, function(Index, Value){
				HTML += "<div class='EventAttachedContact'>"+(Value['ReadOnly'] ? "<span title='You dont have permission to view this contacts information'>"+Value['ContactName']+"</span>" : "<a href='/app/View_Contact?ContactId="+Value['ContactId']+"' class='EventAttachedLink'>"+Value['ContactName']+"</a>")+
					"<img src='/i/app/tag_close.png' onclick='EventObject.RemoveContact("+Value['ContactId']+");' height='13' width='13' style='cursor:pointer; position:absolute; right:3px; top:2px;' /></div>";
				$('#EventDialog_Form').append("<input type='hidden' class='EventFormAttachedContact' name='Contact["+Value['ContactId']+"]' value='true' />");
			});
			
			HTML +=
				"<br style='clear:both;' /><div style='padding:5px 0px;'><a href='javascript://' class='EventAttachedContactLink ShowAttachContactMenu' style='font-size:11px;'>Attach another contact</a></div>"
				"</div>";
			$('#EventDialog_Contacts').html(HTML);
		}
		
		$('.ShowAttachContactMenu').bind('click', function(e){
			EventObject.ShowAttachContactMenu(e);
		})
	}
	
	this.ContactSearchCount = 0;
	this.ShowAttachContactMenu = function(event){
		event.stopPropagation();
		
		if($('#EventAttachContactDiv').length > 0){
			$('#EventAddContactSearchField').focus();
			return;
		}
		$('#EventDialog_Contacts').append("<div id='EventAttachContactDiv' class='EventAttachContactDiv' style='display:none;'><div align='right'><a href='javascript://' onclick='$(\"#EventAttachContactDiv\").remove();' style='font-size:11px;'>Close</a></div>"
		+"<div class='BoldGray'>Search for a contact to attach...</div><div><input id='EventAddContactSearchField' type='text' class='BoldFormField' style='width:220px;' /></div><div id='EventContactSearchResults' style='min-height:50px; margin-top:10px;' ></div>"
		+"</div>");
		
		//$('#EventAddContactSearchField').focus();
		
		$('#EventAttachContactDiv').bind("keyup", function(){
			EventObject.ContactSearchCount++;
			EndGrayOutArea('#EventContactSearchResults');
			GrayOutArea('#EventContactSearchResults', true);
			setTimeout("EventObject.ContactSearch("+EventObject.ContactSearchCount+")", 750);
		});
		
		ShowDropdown(".EventAttachContactDiv", ".EventAttachedContactLink", "EventObject.HideAttachContactMenu()");
		$('#EventAddContactSearchField').focus();
	}
	
	this.HideAttachContactMenu = function(){
		$('#EventAttachContactDiv').remove();
	}
	
	this.ContactSearch = function(Count){
		if(Count == this.ContactSearchCount){
			$.post("/appinclude/action/calendar/search_contacts.php", {SearchTerms:$('#EventAddContactSearchField').val()}, function(Data){
				InsertMarkupFromAJAX(Data);
			});
		}
	}
	
	this.AttachContact = function(ContactId, ContactName){
		var TempArray = {"ContactId":ContactId, "ContactName":ContactName, "ReadOnly":false};
		this.AttachedContacts.push(TempArray);
		this.HideAttachContactMenu();
		this.DrawAttachedContacts();
	}
	
	this.RemoveContact = function(ContactId){
		var TempIndex = -1;
		$.each(this.AttachedContacts, function(Index, Value){
			if(Value['ContactId'] == ContactId)
				TempIndex = Index;
		});
		if(TempIndex != -1){
			EventObject.AttachedContacts.splice(TempIndex, 1);
			this.DrawAttachedContacts();
		}
	}
	
	this.DrawAttachedUsers = function(){
		$('.EventFormAttachedUser').remove();
		
		if($('#EventOtherUserSource').length == 0)
			return;
		
		if(this.AttachedUsers.length == 0){
			$('#EventDialog_Users').html("<a href='javascript://' class='ShowAttachUserMenu IconSprite IconSprite-add_translucent' class='Icon'></a>"+
				" <a href='javascript://' class='ShowAttachUserMenu' style='font-size:11px;'>Add another user from your company</a>");
			$('#EventDialog_ReminderSection').show();
		}
		else{
			var HTML = "";
			
			HTML += ""+
				"<div style='padding:5px; background-color:#eee; margin-top:12px;'>"+
				"<div class='BoldGray' align='center' style='margin-bottom:10px;'>Users Attending</div>";
			
			var UserIsAttending = this.UserIsAttending();
			$.each(this.AttachedUsers, function(Index, Value){
				if(Value == 39944)
					UserIsAttending = true;
				HTML += "<div class='EventAttachedUser'>"+$('#EventAttachUserName_'+Value).html()+
					"<img src='/i/app/tag_close.png' onclick='EventObject.RemoveUser("+Value+");' height='13' width='13' style='cursor:pointer; position:absolute; right:3px; top:2px;' /></div>";
				$('#EventDialog_Form').append("<input type='hidden' class='EventFormAttachedUser' name='User["+Value+"]' value='true' />");
			});
			
			if(UserIsAttending)
				$('#EventDialog_ReminderSection').show();
			else{
				$('#EventDialog_ReminderSection').hide();
			}
			HTML +=
				"<br style='clear:both;' /><div style='padding:5px 0px;'><a href='javascript://' class='EventAttachedContactLink ShowAttachUserMenu' style='font-size:11px;'>Attach another user</a></div>"
				"</div>";
			$('#EventDialog_Users').html(HTML);
		}
		
		$('.ShowAttachUserMenu').bind('click', function(e){
			EventObject.ShowAttachUserMenu(e);
		})
	}
	
	this.UserIsAttending = function(){
		var UserIsAttending = false;
		$.each(this.AttachedUsers, function(Index, Value){
			if(Value == 39944)
				UserIsAttending = true;
		});
		return UserIsAttending;
	}
	
	this.AttachUser = function(UserId){
		this.AttachedUsers.push(UserId);
		this.HideAttachUserMenu();
		this.DrawAttachedUsers();
	}
	
	this.RemoveUser = function(UserId){
		var TempIndex = -1;
		$.each(this.AttachedUsers, function(Index, Value){
			if(Value == UserId)
				TempIndex = Index;
		});
		if(TempIndex != -1){
			EventObject.AttachedUsers.splice(TempIndex, 1);
			this.DrawAttachedUsers();
		}
	}
	
	this.ShowAttachUserMenu = function(event){
		event.stopPropagation();
		$('#EventDialog_Users').append("<div id='EventAttachUserDiv' class='EventAttachContactDiv'><div align='right'><a href='javascript://' onclick='$(\"#EventAttachUserDiv\").remove();' style='font-size:11px;'>Close</a></div>"
		+"<div class='BoldGray'>Select the user to attach...</div><div>We will send an email notifying any users you invite.</div><div id='EventContactSearchResults' style='min-height:50px; margin-top:10px; max-height:300px; overflow:auto;' >"+$('#EventOtherUserSource').html()+"</div>"
		+"</div>");
		
		ShowDropdown("#EventAttachUserDiv", ".EventAttachedUserLink", "EventObject.HideAttachUserMenu()");
	}
	
	this.HideAttachUserMenu = function(){
		$('#EventAttachUserDiv').remove();
	}
	
	this.DeleteReminder = function(ReminderCount){
		$('#EventReminder_'+ReminderCount).remove();
	}
	
	this.SaveEvent = function(){
		if(!this.Validate())
			return;
		
		if(this.EditEventId == 0)
			var PostURL = "/appinclude/action/calendar/save_event.php";
		else
			var PostURL = '/appinclude/action/calendar/edit_event.php?EventId='+this.EditEventId;
		
		
		$('#EventDialog_ContactId').val(ViewContactObject.ContactId);

		var Params = $('#EventDialog_Form').serialize();
		Params += "&EventDate="+ encodeURI(Date.parse($('#EventDialog_DatePicker').datepicker("getDate")).toString("yyyy-MM-dd"));
		
		GrayOutArea('#EventDialog_Form', true);
		$.post(PostURL, Params, function(Data){
			InsertMarkupFromAJAX(Data);			
		});
		
	}
	
	this.Validate = function(){
		var CurrentDate = $('#EventDialog_DatePicker').datepicker("getDate");
		
		if(!CurrentDate){
			alert("Please pick a date");
			return false;
		}
		else
			$('#EventDialog_Date').val(CurrentDate);
		
		if(!Date.parse($('#EventDialog_StartTime').val())){
			alert("Please enter a valid start time");
			return false;
		}
		if(!Date.parse($('#EventDialog_EndTime').val())){
			alert("Please enter a valid end time");
			return false;
		}
		if(Date.parse($('#EventDialog_EndTime').val()) < Date.parse($('#EventDialog_StartTime').val())){
			alert("Please make sure that the event's end time is after the start time");
			return false;
		}
		
		if($('#EventDialog_Name').val() == ''){
			alert('Please enter a name for the event');
			return false;
		}
		
		return true;
		//VALIDATE
		//Reminder times are actual numbers
		//Start Time is before end time
	}
	
	this.RemoveTimeDropdown = function(){
		$('.EventTimeDropdownDiv').remove();
	}
	
	this.LoadSchedule = function(){
		return;
		GrayOutArea('#EventDialog_Schedule', true);
		$.post('/appinclude/action/calendar/get_availability.php', $('#EventDialog_Form').serialize(), function(Data){
			InsertMarkupFromAJAX(Data);
		});
	}
	this.UpdateSchedule = function(){
		
	}
	
	this.Delete = function(){
		var MoreUsers = false;
		var ThisUser = false
		$.each(this.AttachedUsers, function(Index, Value){
			if(Value != 39944)
				MoreUsers = true;
			else
				ThisUser = true
		});
		
		CloseDialogFromSource("NewEvent");
		
		if(MoreUsers && ThisUser){
			Dialog("<div id='EventDeleteConfirm' style='padding:20px;'><div class='BoldGray' align='center'>There are other users attending this event. Do you want to delete the event for all users, or just remove it from your own calendar?</div><br /><br /><div align='center'><span class='BoldGray'><a href='javascript://' onclick='EventObject.ConfirmDelete();'>Delete the event</a></span><span style='padding:20px;'></span><span class='BoldGray'><a href='javascript://' onclick='EventObject.RemoveFromCalendar();'>Remove from my calendar</a></span><span style='padding:20px;'></span><a href='javascript://' onclick='CloseDialog($(this).parent())' style='color:#999;'>Cancel</a></div>");
		}
		else{
			Dialog("<div id='EventDeleteConfirm' class='BoldGray' align='center' style='padding:20px;'><div>Are you sure you want to delete this event?</div><br /><br /><div align='center'><span class='BoldGray'><a href='javascript://' onclick='EventObject.ConfirmDelete();'>Yes, delete the event</a></span><span style='padding:20px;'></span><a href='javascript://' onclick='CloseDialog($(this).parent())' style='color:#999;'>Cancel</a></div></div>");
		}
	}
	
	//
	this.ConfirmDelete = function(){
		GrayOutArea('#EventDeleteConfirm', true);
		$.post('/appinclude/action/calendar/delete.php', {EventId:this.EditEventId, ContactId:ViewContactObject.ContactId}, function(Data){
			InsertMarkupFromAJAX(Data);
			CloseDialogs();
			
			try{
				if(CurrentPage.toLowerCase() == '/app/calendar/view'){
					CalendarObject.GetEvents();
				}
			}
			catch(err){	}
		});
	}
	
	//this removes the user from an event
	this.RemoveFromCalendar = function(){
		$.post('/appinclude/action/calendar/remove_user.php', {EventId:this.EditEventId}, function(Data){
			InsertMarkupFromAJAX(Data);
			CloseDialogs();
			
			try{
				if(CurrentPage.toLowerCase() == '/app/calendar/view'){
					CalendarObject.GetEvents();
				}
			}
			catch(err){	}
		});
	}
}

</SCRIPT>

<DIV style="display: none;" id="DialogWrapper_NewEvent">
<DIV id="DialogSource_NewEvent">
<DIV id="EventDialogWriteDiv">
<DIV class="DialogHeader">
<DIV class="EventDialog_New" align="center">Create a new event</DIV>
<DIV class="EventDialog_Edit" align="center">Edit Event</DIV></DIV>
<DIV style="padding: 20px; font-size: 13px;">
<FORM id="EventDialog_Form" accept-charset="UTF-8">
<TABLE cellSpacing="0" cellPadding="0" width="100%">
  <TBODY>
  <TR>
    <TD vAlign="top" width="400">
      <DIV style="color: rgb(102, 102, 102);" class="BoldGray">				Event Name
      			</DIV>
      <DIV><INPUT style="width: 445px;" id="EventDialog_Name" class="BoldFormField" 
      name="Name" type="text"></DIV>
      <TABLE style="margin-top: 20px;" cellSpacing="0" cellPadding="0">
        <TBODY>
        <TR>
          <TD style="padding-right: 20px;" vAlign="top">
            <DIV style="color: rgb(102, 102, 102); margin-bottom: 3px;" class="BoldGray">
            						Date					</DIV>
            <DIV style="font-size: 11px;" 
            id="EventDialog_DatePicker"></DIV><INPUT id="EventDialog_Date" name="Date" 
            type="hidden"></TD>
          <TD vAlign="top">
            <DIV style="color: rgb(102, 102, 102); margin-bottom: 3px;" class="BoldGray">
            						Time						<SPAN style="color: rgb(153, 153, 153); padding-left: 10px; font-size: 10px; font-weight: normal;"></SPAN></DIV><INPUT 
            style="width: 85px;" id="EventDialog_StartTime" class="BoldFormField" 
            name="StartTime" type="text"><SPAN style="padding: 0px 4px; color: rgb(102, 102, 102);" 
            class="BoldGray">to</SPAN><INPUT style="width: 85px;" id="EventDialog_EndTime" 
            class="BoldFormField" name="EndTime" type="text">
            <DIV style="color: rgb(102, 102, 102); margin-top: 8px; margin-bottom: 3px;" 
            class="BoldGray">						Event Description					</DIV><TEXTAREA style="width: 215px; height: 100px; font-size: 12px; font-weight: normal;" id="EventDialog_Description" class="BoldFormField" name="Description"></TEXTAREA></TD></TR></TBODY></TABLE>
      <DIV id="EventDialog_ReminderSection">
      <DIV style="color: rgb(102, 102, 102); padding-bottom: 3px; margin-top: 30px; margin-bottom: 3px; border-bottom-color: rgb(204, 204, 204); border-bottom-width: 1px; border-bottom-style: solid;" 
      class="BoldGray">				Reminders				<SPAN style="color: rgb(153, 153, 153); padding-left: 20px; font-size: 10px; font-weight: normal;"><!--Manage your default reminders in the settings section--></SPAN></DIV>
      <DIV id="EventDialog_ReminderSource"></DIV>
      <DIV style="margin-top: 5px;"><A style="color: rgb(153, 153, 153);" 
      onclick="EventObject.AddReminder();" href="javascript://">Add a 
      reminder</A></DIV></DIV>
      <DIV style="margin-top: 30px;"><A style="width: 352px; padding-right: 70px; padding-left: 70px;" 
      class="EventDialog_New GreenButton" onclick="EventObject.SaveEvent();" 
      href="javascript://">Save this event</A><A style="width: 352px; padding-right: 70px; padding-left: 70px;" 
      class="EventDialog_Edit GreenButton" onclick="EventObject.SaveEvent();" 
      href="javascript://">Save Changes</A><SPAN style="color: rgb(153, 153, 153); padding-right: 15px; padding-left: 15px;">or</SPAN><A 
      onmousedown='CloseDialogFromSource("NewEvent");' 
      href="javascript://">Cancel</A></DIV></TD>
    <TD style="padding-top: 10px; padding-left: 40px;" id="TempEventDiv" vAlign="top">
      <DIV style="position: relative;" id="EventDialog_Contacts"></DIV>
      <DIV style="position: relative;" id="EventDialog_Users"></DIV>
      <DIV style="position: relative; min-height: 100px;" id="EventDialog_Schedule"></DIV></TD></TR></TBODY></TABLE><INPUT 
id="EventDialog_ContactId" name="ContactId" type="hidden"></FORM></DIV>
<DIV style="padding: 10px 20px;" class="DialogFooter EventDialog_Edit" align="right">
<DIV style="font-size: 13px;" align="right"><A style="top: -1px; position: relative;" 
class="IconSprite IconSprite-bin" onclick="EventObject.Delete();" href="javascript://">Delete 
this event</A><A style="padding-left: 4px;" onclick="EventObject.Delete();" 
href="javascript://">Delete this event</A></DIV></DIV></DIV>
<DIV style="display: none;" id="EventDialogReadDiv"></DIV></DIV></DIV></DIV>
<DIV id="AJAXPAGE_js__opportunity" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">

var OpportunityObject = new OpportunityClass();	

function OpportunityClass(){
	this.SelectedDate;
	this.SetReminder = 0;
	this.PipelineId = 0;
	this.OpportunityId;
	this.Opportunity;
	this.Contact;
	this.PageType;
	this.ReadOnly;
	
	this.NewOpportunity = function(PipelineId, Contact, PageType){
		this.PageType = PageType
		this.PipelineId = PipelineId;
		AddContactObject.PipelineId = PipelineId;
		this.Contact = Contact;
		this.ContactId = Contact['ContactId'];		
		
		if(PageType != null)
			this.PageType = PageType
		else
			this.PageType = "";
		
		DialogFromSource("AddContactForm",920);
		
		this.ResetForm();
		
		AddContactObject.FormType = 'NewOpportunity';
		
		$('#AddOpportunity_OpportunityId').val("0");
		$('#AddOpportunity_ContactId').val(this.Contact['ContactId']);
		$('#CreateContactButton').attr("value", "Save "+$('#PipelineSourceName_'+PipelineId).html());
		$('#AddOpportunity_PipelineId').val(PipelineId);
		
		$('.ContactDialog_OpportunityNew').show();
		$('.ContactDialog_OpportunityEdit').hide();
		
		$('.AddOpportunityCustomFields').hide();
		$('.AddOpportunityToNewContact_'+PipelineId).show();
		
		$('[id^="AddContactStatus_"]').each(function(){
			$(this).find(":first-child").attr("selected", "selected");
		});
	}
	
	this.UpdateOpportunity = function(ThisOpportunityId, PageType, IsCompanyFeed){
		CloseDialogs();
		Dialog("<div style='text-align:center; padding:150px 75px;'><img src='style/default/images/main/loading.gif' /></div>",920);
		this.OpportunityId = ThisOpportunityId;
		
		if(PageType != null)
			this.PageType = PageType;
		else
			this.PageType = "";
		
		$('#CreateContactButton').attr("value", "Update this "+$('#PipelineSourceName_'+ThisOpportunityId).html()+"");
		
		$.post("/appinclude/action/get_opportunity.php", {OpportunityId:ThisOpportunityId}, function(Data){
			CloseDialogs();
			InsertMarkupFromAJAX(Data);
			
			//console.log(OpportunityObject.Opportunity);
			
			if(OpportunityObject.ReadOnly == 1){
				return;
			}
			
			OpportunityObject.PipelineId = OpportunityObject.Opportunity['PipelineId'];
			AddContactObject.PipelineId = OpportunityObject.Opportunity['PipelineId'];
			
			OpportunityObject.ResetForm();
			
			AddContactObject.FormType = 'UpdateOpportunity';
			
			$('.ContactDialog_OpportunityNew').hide();
			$('.ContactDialog_OpportunityEdit').show();
			$('#OpportunityActivityWrapper').show();
			$('.AddOpportunityCustomFields').hide();
			$('.AddOpportunityToNewContact_'+OpportunityObject.Opportunity['PipelineId']).show();
			
			$('.OpportunityContactSName').html(OpportunityObject.Contact['SName']);
			$('#AddContactPriority').val(OpportunityObject.Opportunity['Priority']);
			$('#AddOpportunity_OpportunityId').val(OpportunityObject.OpportunityId);
			$('#AddOpportunity_ContactId').val(OpportunityObject.ContactId);
			$('#AddOpportunity_IsCompanyFeed').val((IsCompanyFeed ? "1" : "0"));
			$('#AddContactStatus_'+OpportunityObject.PipelineId).val(OpportunityObject.Opportunity['StatusId']);
			$('.DeleteOpportunityName').html($('#PipelineSourceName_'+OpportunityObject.PipelineId).html());
			
			//Set the custom field values
			jQuery.each(OpportunityObject.Opportunity['CustomData'], function(Index, Val){
				if(typeof(Val)=='object'){
					jQuery.each(Val, function(j, CheckVal){
						$('.PipelineFieldOption_'+Index+"_"+CheckVal).attr('checked', 'checked');
					});
				}
				else{
					$('#PipelineField_'+Index).val(Val);
				}
			});
			
			$('#CreateContactButton').attr("value", "Update this "+$('#PipelineSourceName_'+OpportunityObject.Opportunity['PipelineId']).html()+"");
			
			DialogFromSource("AddContactForm",920);
			
		});
	}
	
	this.ResetForm = function(){
		this.SetReminder = 0;
		
		$('.ContactDialog_Opportunity').show();
		$('.ContactDialog_ContactForm').hide();
		$('.ContactDialog_Pipeline').hide();
		$('.AddContactStatusOptions').hide();
		$('.AddOpportunityPipelineWrapper').hide();
		$('.ContactDialog_Pipeline_'+this.PipelineId).show();
		$('#AddOpportunityToNewContact_'+this.PipelineId).show();
		$('#AddContactStatusUpdate').show();
		$('#AddContactStatusOptions_'+this.PipelineId).show();
		$('#OpportunityActivityWrapper').hide();
		
		$('#AddOpportunity_OpportunityId').val('');
		$('#AddOpportunity_PipelineId').val('');
		$("#AddContactPipelineId").val("0");
		$('#AddContactReminderSet').val(0);
		$('#AddContactNoteSet').val(0);
		AddContactObject.SetReminder = 0;
		AddContactObject.SaveNote = 0;
		
		$('.PipelineFormCustomField').attr('checked', false);
		$('.PipelineFormCustomField').val('');
		$('#AddContactStylingDiv').find('select option:first-child').attr("selected", "selected");
		$('.AddContactStatus').attr('checked', false);
		$('#AddContactPriority').val('');
		$('#AddContactStatusNote').val('');
		$('#NewPipelineReminderUserId').val(39944);
		$('#AddContactReminderDescription').val('');
		$("#AddContactNoteLink").show();
		$("#AddContactNoteDiv").hide();
		
		$("#AddContactReminderDiv").hide();
		$("#AddContactReminderLink").show();
		
		$('#AddContactReminderDate').datepicker({
			inline: true,
			numberOfMonths:2,
			onSelect:function(datetext, inst){
				AddContactObject.SetSpecificDate(datetext, inst);
			}
		});
		
		this.SelectedDate = ReminderObject.Today;
		$('#AddContactSelectedDate').val(this.SelectedDate);
		$('#AddContactReminderDate').datepicker('setDate', new Date(ReminderObject.Today));
		
		$('.OpportunityContactName').html(this.Contact['ShortName']);
		
	};
	
	this.SetSpecificDate = function(datetext, inst){
		this.SelectedDate = datetext;
		$('#AddContactSelectedDate').val(this.SelectedDate);
	}
	
	this.ShowSummary = function(ThisOpportunityId){
		CloseDialogs();
		Dialog("<div class='OpportunityOverviewDialog'><div  style='text-align:center; padding:150px 75px;'><img src='style/default/images/main/loading.gif' /></div></div>"
			,720);
		
		$.post("/appinclude/action/opportunity_overview.php", {OpportunityId:ThisOpportunityId}, function(Data){
			InsertMarkupFromAJAX(Data);
			RepositionDialogs();
		});
		
	}
	
	this.DeleteOpportunity = function(){
		CloseDialogFromSource("AddContactForm");
		Dialog("<div class='DeleteOpportunityConfirmDialog'><div style='padding:20px;'><div class='BoldGray'>Are you sure you want to delete this "+$('#PipelineSourceName_'+OpportunityObject.PipelineId).html()+"? This will remove everything including related status updates and notes. \
				If you just want to close it instead of deleting it, you should update the status to a closed status.</div>\
				<br ><div align='center' class='BoldGray'><strong><a href='javascript://' onclick='OpportunityObject.ConfirmDeleteOpportunity();'>Yes, delete this</a></strong> <span style='padding-left:20px;'><a href='javascript://' onclick='CloseDialogs();' style='color:#999; font-size:13px; font-weight:normal'>cancel</a></span></div></div></div>");
	}
	
	this.ConfirmDeleteOpportunity = function(){
		GrayOutArea(".DeleteOpportunityConfirmDialog", true);
		$.post("/appinclude/action/opportunity/delete_opportunity.php", {OpportunityId:this.OpportunityId}, function(Data){
			CloseDialogs();
			InsertMarkupFromAJAX(Data);
		});
	}
}

</SCRIPT>
<SPAN id="PipelineSourceName_47557">Lead</SPAN><SPAN id="PipelineSourceSName_47557">Leads</SPAN><SPAN 
id="PipelineSourceName_47560">bills</SPAN><SPAN 
id="PipelineSourceSName_47560">bills</SPAN></DIV>
<DIV id="AJAXPAGE_js__add_contact" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">var CompanyAutoComplete = ["RookieSoft"]</SCRIPT>

<STYLE>
table .AddContactExtraField{
	font-size:10px;
	font-weight:normal;
	color:#999999;
}

.BoldFormField, table .BoldFormField{
	font-size:14px;
}

.CompanyOnlyField{
	display:none;
}

</STYLE>

<SCRIPT type="text/javascript">

$(function(){
	$('.PipelineDateField').each(function(){
		$(this).datepicker({
			changeMonth: true,
			changeYear: true,
			dateFormat: "mm/dd/yy",
			showAnim: "slideDown",
			beforeShow: function(input, datepicker) {
				setTimeout(function() {
					$(datepicker.dpDiv).css('zIndex', 9999999);
				}, 250);
			},
		});	
	});
});

var AddContactObject = new AddContactClass();	

function AddContactClass(){
	this.EmailCount = 1;
	this.PhoneCount = 1;
	this.AddressCount = 1;
	this.IMCount = 1;
	this.WebsiteCount = 1;
	this.SelectedDate;
	this.SetReminder = 0;
	this.PipelineId = 0;
	this.FormType; //can be Contact, NewOpportunity, UpdateOpportunity
	this.SaveNote = 0;
	
	this.NewForm = function(Type, CompanyName, PipelineId){
		DialogFromSource("AddContactForm",920);
		this.ResetForm();
		if(Type == 'Company'){
			this.SwitchToCompanyForm();
		}
		else{
			if(CompanyName != null)
				$('#CompanyName').val(CompanyName);
		}
		
		if(PipelineId != null){
			this.ShowOpportunityOptions(PipelineId);
		}
	}
	
	this.ResetForm = function(){
		this.FormType = 'Contact';
		
		//Make a call to the server to update the list of companies for the autocomplete
		$.post("/appinclude/action/autocomplete/refresh_companies.php", {}, function(data){
			InsertMarkupFromAJAX(data);
		});
		
		$('.ContactDialog_Opportunity').hide();
		$('.ContactDialog_OpportunityNew').hide();
		$('.ContactDialog_OpportunityEdit').hide();
		$('.ContactDialog_ContactForm').show();
		
		$('#AddContactNameWarning').hide();
		$('#AddContactNameDetailWarning').hide();
		$('#AddContactCompanyNameWarning').hide();
		$('.DuplicateEmailWarning').hide();
		
		//show all hidden fields (so they can be cleared)
		$('#AddContactNameDetails').show();
		$('#AddContactNameSimple').show();
		
	
		$('#AddContactStylingDiv').find(':input','#AddContactForm')
			 .not(':button, :submit, :reset, :hidden')
			 .val('')
			 .removeAttr('checked')
			 .removeAttr('selected');
		
		$('#UseNameDetails').val(0);
		
		$('#AddContactNameDetails').hide();
		
		this.EmailCount = 1;
		this.PhoneCount = 1;
		this.AddressCount = 1;
		this.IMCount = 1;
		this.WebsiteCount = 1;
		this.SetReminder = 0;
		this.SaveNote = 0;
		this.PipelineId = 0;
		
		$('#CreateContactButton').attr("value", "Create Contact");
		$("#AddContactPipelineId").val("0");
		$('#AddContactReminderSet').val(0);
		$('.PipelineFormCustomField').attr('checked', false);
		$('.PipelineFormCustomField').val('');
		$('#AddOpportunity_OpportunityId').val('');
		$('#AddOpportunity_PipelineId').val('');
		$('#AddOpportunity_OpportunityId').val("0");
		$('#AddOpportunity_ContactId').val('');
		$('#AddOpportunity_IsCompanyFeed').val(0);
		
		$('[id*=ExpandedField]').hide();
		$('.AddContactExtraFields').hide();
		$('[id*=ShowFieldLink]').show();
		$('.AddOpportunityCustomFields').hide();
		$('.AddOpportunityPipelineWrapper').hide();
		
		$('#AddContactStylingDiv').find('select option:first-child').attr("selected", "selected");
		AddTextAreaDefault("#BackgroundInfo", "Use this space to enter any information that doesn't fit in one of the fields above (e.g., how you met, name of spouse, etc)", '#bbbbbb');
		
		AddTextAreaDefault("[id^=Address][id*=Street]", "Street", "#bbbbbb");
		AddTextAreaDefault("[id^=Address][id*=City]", "City", "#bbbbbb");
		AddTextAreaDefault("[id^=Address][id*=State]", "State", "#bbbbbb");
		AddTextAreaDefault("[id^=Address][id*=Zip]", "Zip", "#bbbbbb");
		AddTextAreaDefault("[id^=Address][id*=Country]", "Country", "#bbbbbb");
		
		this.SwitchToContactForm();
		
		if(CurrentPageParams['CompanyName'] != null){
			$('#CompanyName').val(CurrentPageParams['CompanyName']);
		}
		
		if(CurrentPageParams['IsCompany'] != null){
			this.SwitchToCompanyForm();
		}
		
		$('[id^="AddOpportunityToNewContact"]').hide();
		$('#AddContactStatusUpdate').hide();
		$('#AddContactPipelineTags').show();
		$("#AddContactReminderDiv").hide();
		$("#AddContactReminderLink").show();
		$('.AddContactStatus').attr('checked', false);
		$('#AddContactPriority').val('');
		$('#AddContactStatusNote').val('');
		$('#NewPipelineReminderUserId').val(39944);
		$('#AddContactReminderDescription').val('');
		$("#AddContactNoteLink").show();
		$("#AddContactNoteDiv").hide();
		$('#OpportunityActivityWrapper').hide();
		
		$('#AddContactReminderDate').datepicker({
			inline: true,
			numberOfMonths:2,
			onSelect:function(datetext, inst){
				AddContactObject.SetSpecificDate(datetext, inst);
			}
		});
		
		this.SelectedDate = ReminderObject.Today;
		$('#AddContactSelectedDate').val(this.SelectedDate);
		$('#AddContactReminderDate').datepicker('setDate', new Date(ReminderObject.Today));
		
		$('[id^="AddContactStatus_"]').each(function(){
			$(this).find(":first-child").attr("selected", "selected");
		});
		
		$('#Name').focus();
	};
	
	this.SetSpecificDate = function(datetext, inst){
		this.SelectedDate = datetext;
		$('#AddContactSelectedDate').val(this.SelectedDate);
	}
	
	this.AddField = function(FieldType, ThisCount){
		$('#'+FieldType+'Fields').find('.AddContactExtraField').parent().before('<div class="AddContactExtraFields">'+$('#MultiForm_'+FieldType).html().replace(/xxx/g, ThisCount)+'</div>');
		
		if(FieldType == 'Address'){
			AddTextAreaDefault("[id^=Address][id*=Street]", "Street", "#bbbbbb");
			AddTextAreaDefault("[id^=Address][id*=City]", "City", "#bbbbbb");
			AddTextAreaDefault("[id^=Address][id*=State]", "State", "#bbbbbb");
			AddTextAreaDefault("[id^=Address][id*=Zip]", "Zip", "#bbbbbb");
			AddTextAreaDefault("[id^=Address][id*=Country]", "Country", "#bbbbbb");
		}
		
		//Focus on the first form field for the new element
		if($('#'+FieldType+'_'+ThisCount).find("textarea").length > 0){
			//This is the address field
			$('#'+FieldType+'_'+ThisCount).find("textarea").focus();
		}
		else{
			$('#'+FieldType+'_'+ThisCount).find("input:first").focus();
		}
		
		eval("this."+FieldType+"Count++");
	}

	this.RemoveField = function(FieldType, ThisCount){
		$('#'+FieldType+'_'+ThisCount).remove();
	}
	
	this.ShowCollapsedField = function(FieldId){
		$('#ShowFieldLink_'+FieldId).hide();
		$('#ExpandedField_'+FieldId).show();
		
		if($('#ExpandedField_'+FieldId).find("textarea").length > 0){
			//This is the address field
			$('#ExpandedField_'+FieldId).find("textarea").focus();
		}
		else{
			$('#ExpandedField_'+FieldId).find("input:first").focus();
		}
	}
	
	this.ShowNameDetails = function(){
		$('#AddContactNameSimple').hide();
		$('#AddContactNameDetails').show();
		$('#UseNameDetails').val(1);
		
		var SimpleName = $('#Name').val().trim().split(" ");
		var FirstName = "";
		var MiddleName = "";
		var LastName = "";
		
		if(SimpleName.length == 1){
			FirstName = SimpleName[0];
		}
		else if(SimpleName.length == 2){
			FirstName = SimpleName[0];
			LastName = SimpleName[1];
		}
		else if(SimpleName.length > 2){
			FirstName = SimpleName[0];
			for(var i=1; i < SimpleName.length - 1; i++){
				if(i > 1)
					MiddleName += " ";
				MiddleName += SimpleName[i];
			} 
			LastName = SimpleName[SimpleName.length - 1];
		}
		
		$('.FirstName').val(FirstName);
		$('.MiddleName').val(MiddleName);
		$('.LastName').val(LastName);
	}
	
	this.SwitchToCompanyForm = function(){
		$('.CompanyOnlyField').show();
		$('.ContactOnlyField').hide();
		$('#AddContactNameDetails').hide();
		$('#AddContactNameSimple').show();
		
		$('#CreateContactButton').attr('value', 'Create Company');
		
		$('#AddContactIsCompany').val(1);
	}
	
	this.SwitchToContactForm = function(){
		$('.CompanyOnlyField').hide();
		$('.ContactOnlyField').show();
		
		$('#CreateContactButton').attr('value', 'Create Contact');
		
		$('#AddContactIsCompany').val(0);
	}
	
	this.AddContact = function(){
		if(this.FormType == 'Contact'){
			if($('#AddContactIsCompany').val() == 1){
				if($('#Name').val() == ''){
					alert("Please enter a name for this company");
					return;
				}
			}
			else{
				if($('#UseNameDetails').val() == 1){
					if($('.FirstName').val() == '' && $('.LastName').val() == ''){
						alert("Please enter a first name or a last name for this contact");
						return;
					}
				}
				else{
					if($('#Name').val() == ''){
						alert("Please enter a name for this contact");
						return;
					}
				}
			}
		}
		
		//Check to see if any custom fields are required but not filled out
		var CustomFields = $(".RequiredPipelineField:visible");
		for(i = 0; i < CustomFields.length; i++){
			var ThisField = CustomFields[i];
			if($(ThisField).val() == ''){
				alert("Please fill in the "+$(ThisField).attr('FieldName')+" field.");
				return false;
			}
		}
		
		var DateFields = $('.PipelineDateField:visible');
		for(i=0;i<DateFields.length;i++){
			var ThisField = DateFields[i];
			if($(ThisField).val() != '' && !ValidateDate($(ThisField).val(), false)){
				alert("The "+$(ThisField).attr('FieldName')+" field must contain a valid date (mm/dd/yyyy)");
				return false;
			}
		}
		
		var NumberFields = $('.PipelineNumberField:visible');
		for(i=0;i<NumberFields.length;i++){
			var ThisField = NumberFields[i];
			if($(ThisField).val() != '' && !ValidateNumber(CleanNumber($(ThisField).val(), ($(ThisField).attr('EuropeanFormat') == 1 ? true : false)))){
				alert("The "+$(ThisField).attr('FieldName')+" field must be a number");
				return false;
			}
		}
		
		if(this.SetReminder == 1 && $('#AddContactReminderDescription').val() == ''){
			alert("Please enter a task name (or remove the task)");
			return false;
		}
		
		if(this.FormType == 'Contact')
			LogAnalyticsEvent("New Contact", "CRM");
		if(this.SetReminder)
			LogAnalyticsEvent("New Task", "Calendar");
		if(this.PipelineId > 0)
			LogAnalyticsEvent("Update Pipeline", "CRM");
		
		GrayOutArea("#ContactFormDialogWrapper", true);
		$.post("/appinclude/action/add_contact.php", $('#AddContactForm').serialize(), function(Data){
			EndGrayOutArea();
			
			//CloseDialogs();
			//Dialog(Data);
			InsertMarkupFromAJAX(Data);
			
			if(OpportunityObject.PageType == "Report" && AddContactObject.FormType == 'UpdateOpportunity'){
				//We're looking at a report, so it should be updated
				ActiveReportObject.BuildNewURL(true);
			}
		});
	}
	
	this.ShowOpportunityOptions = function(PipelineId){
		$('#AddContactPipelineTags').hide();
		$('.AddOpportunityToNewContact_'+PipelineId).slideDown('fast');
		$('#AddContactStatusUpdate').slideDown('fast');
		$('.AddContactStatusOptions').hide();
		$('#AddContactStatusOptions_'+PipelineId).show();
		
		this.PipelineId = PipelineId;
		$('#AddContactPipelineId').val(PipelineId);
		
		$('#CreateContactButton').attr("value", "Create Contact and attach "+$('#PipelineSourceName_'+PipelineId).html());
	}
	
	this.CancelOpportunityOptions = function(PipelineId){
		$('#AddContactStatusUpdate').slideUp('fast');
		$('.AddOpportunityToNewContact_'+PipelineId).slideUp('fast', function(){
			$('#AddContactPipelineTags').slideDown('fast');
		});
		
		$("#AddContactReminderDiv").hide();
		$("#AddContactReminderLink").show();
		
		this.PipelineId = 0;
		$('#AddContactPipelineId').val(0);
		$('#CreateContactButton').attr("value", "Create Contact");
	}
	
	this.ShowReminderOptions = function(){
		if($('#AddOpportunity_ContactId').val() != '0' && $('#AddOpportunity_ContactId').val() != ''){
			$('#AddContactReminderDescription').val("Follow up with "+OpportunityObject.Contact['ShortName']);
		}
		else{
			if($('#UseNameDetails').val() == '1'){
				$('#AddContactReminderDescription').val("Follow up with "+$('.FirstName').val()+" "+$('.MiddleName').val()+" "+$('.LastName').val());
			}
			else{
				if($('#Name').val() == ''){
					$('#AddContactReminderDescription').val("Follow up");
				}
				else{
					$('#AddContactReminderDescription').val("Follow up with "+$('#Name').val());
				}
			}
		}
		
		$("#AddContactReminderLink").hide();
		$("#AddContactReminderDiv").slideDown('fast');
		$('#AddContactReminderDate').datepicker('setDate', new Date(ReminderObject.Today));
		this.SetReminder = 1;
		$('#AddContactReminderSet').val(1);
	}
	
	this.HideReminderOptions = function(){
		$("#AddContactReminderDiv").slideUp('fast', function(){
			$("#AddContactReminderLink").show();
		});
		this.SetReminder = 0;
		$('#AddContactReminderSet').val(0);
	}
	
	this.ShowNoteField = function(){
		$("#AddContactNoteLink").hide();
		$("#AddContactNoteDiv").slideDown('fast');
		this.SaveNote = 1;
		$('#AddContactNoteSet').val(1);
		$('#AddContactStatusNote').focus();
	}
	
	this.ProcessNewStatus = function(Element){
		if($(Element+" option:selected").text().indexOf("(Closed)") != -1){
			$('#AddContactPriority').val('');
		}
	}
	
	//Code for checking if a duplicate contact exists
	this.CheckDuplicateIndex = function(ThisType, ThisFieldId, Element){
		if($(Element).val() == ""){
			$('#AddContactDuplicateWarning_'+ThisType+'_'+ThisFieldId).slideUp('fast');
			return;
		}
		
		if($('#AddContactDuplicateWarning_'+ThisType+'_'+ThisFieldId).is(":visible")){
			$('#AddContactDuplicateWarning_'+ThisType+'_'+ThisFieldId).html("<img src='style/default/images/main/loading.gif' />");
		}
		
		//$('#AddContactDuplicateWarning_'+Type+'_'+FieldId).fadeIn('slow');
		$.post("/appinclude/action/check_duplicate_index.php", {Type:ThisType, FieldId:ThisFieldId, Value:$(Element).val()}, function(Data){
			InsertMarkupFromAJAX(Data);
		});
	}
	
	this.ShowDuplicateWarning = function(Data){
		Data = jQuery.parseJSON(Data);
		if(Data['ContactId'] == null){
			//There's no duplicate
			$('#AddContactDuplicateWarning_'+Data['Type']+'_'+Data['FieldId']).slideUp('fast');
		}
		else{
			var HTML = "Warning: <a href='/app/View_Contact?ContactId="+Data['ContactId']+"' style='color:white;' onmousedown='CloseDialogFromSource(\"AddContactForm\"); '>"+Data['ContactName']+"</a> "+
				(Data['UserName'] != "" ? "(assigned to "+Data['UserName']+")" : "")+" already has this "+
				(Data['Type'] == 'email' ? "email address" : "phone number")+".";
			
			$('#AddContactDuplicateWarning_'+Data['Type']+'_'+Data['FieldId']).hide();
			$('#AddContactDuplicateWarning_'+Data['Type']+'_'+Data['FieldId']).html(HTML);
			$('#AddContactDuplicateWarning_'+Data['Type']+'_'+Data['FieldId']).slideDown('fast');
		}
	}
	
}

</SCRIPT>

<DIV style="display: none;" id="DialogWrapper_AddContactForm">
<DIV id="DialogSource_AddContactForm">
<FORM id="AddContactForm" onsubmit="AddContactObject.AddContact(); return false;" 
accept-charset="UTF-8" method="post" 
action="/appinclude/action/add_contact.php">
<DIV style="font-size: 34px;" class="DialogHeader ContactDialog_ContactForm">Add 
a <SPAN class="ContactOnlyField">Contact</SPAN><SPAN 
class="CompanyOnlyField">Company</SPAN></DIV>
<DIV class="DialogHeader ContactDialog_Opportunity ContactDialog_Pipeline ContactDialog_Pipeline_47557">
<DIV class="ContactDialog_OpportunityNew">Attach a new Lead to <SPAN class="OpportunityContactName"></SPAN></DIV>
<DIV class="ContactDialog_OpportunityEdit">Update <SPAN class="OpportunityContactSName"></SPAN> 
Lead Status</DIV></DIV>
<DIV class="DialogHeader ContactDialog_Opportunity ContactDialog_Pipeline ContactDialog_Pipeline_47560">
<DIV class="ContactDialog_OpportunityNew">Attach a new bills to <SPAN class="OpportunityContactName"></SPAN></DIV>
<DIV class="ContactDialog_OpportunityEdit">Update <SPAN class="OpportunityContactSName"></SPAN> 
bills Status</DIV></DIV>
<DIV id="ContactFormDialogWrapper">
<DIV style="color: rgb(102, 102, 102); font-size: 14px; font-weight: bold;" id="AddContactStylingDiv">
<DIV style="padding: 20px 20px 0px;" class="ContactDialog_ContactForm"><INPUT 
id="AddContactIsCompany" name="IsCompany" value="0" type="hidden"><INPUT id="UseNameDetails" 
name="UseNameDetails" value="0" type="hidden">
<TABLE style="font-size: 14px;" cellSpacing="0" cellPadding="0" width="100%">
  <TBODY>
  <TR>
    <TD vAlign="top">
      <DIV style="font-size: 12px; display: none;" id="AddContactCompanyNameWarning" 
      class="Warning"></DIV>
      <DIV id="AddContactNameDetails">
      <TABLE style="font-size: 12px;" cellSpacing="0" cellPadding="0">
        <TBODY>
        <TR>
          <TD vAlign="bottom">Salutation</TD>
          <TD vAlign="bottom">First Name</TD>
          <TD vAlign="bottom">Middle Name</TD>
          <TD vAlign="bottom">Last Name</TD>
          <TD vAlign="bottom">Suffix</TD></TR>
        <TR>
          <TD style="padding: 0px 2px;" vAlign="top"><INPUT style="width: 50px; font-size: 10px; font-weight: normal;" 
            id="NameDetails[Salutation]" class="BoldFormField" tabIndex="1" 
            name="NameDetails[Salutation]" maxLength="100" type="text"><SPAN 
            style="display: none;" id="ValSpan_NameDetails[Salutation]"></SPAN> 
          </TD>
          <TD style="padding: 0px 2px;" vAlign="top"><INPUT style="width: 90px; font-size: 12px; font-weight: normal;" 
            id="NameDetails[FirstName]" class="BoldFormField FirstName" 
            tabIndex="1" name="NameDetails[FirstName]" maxLength="100" type="text"><SPAN 
            style="display: none;" id="ValSpan_NameDetails[FirstName]"></SPAN> 
          </TD>
          <TD style="padding: 0px 2px;" vAlign="top"><INPUT style="width: 70px; font-size: 12px; font-weight: normal;" 
            id="NameDetails[MiddleName]" class="BoldFormField MiddleName" 
            tabIndex="1" name="NameDetails[MiddleName]" maxLength="100" type="text"><SPAN 
            style="display: none;" id="ValSpan_NameDetails[MiddleName]"></SPAN> 
          </TD>
          <TD style="padding: 0px 2px;" vAlign="top"><INPUT style="width: 90px; font-size: 12px; font-weight: normal;" 
            id="NameDetails[LastName]" class="BoldFormField LastName" tabIndex="1" 
            name="NameDetails[LastName]" maxLength="100" type="text"><SPAN 
            style="display: none;" id="ValSpan_NameDetails[LastName]"></SPAN> 
</TD>
          <TD style="padding: 0px 2px;" vAlign="top"><INPUT style="width: 40px; font-size: 12px; font-weight: normal;" 
            id="NameDetails[Suffix]" class="BoldFormField" tabIndex="1" name="NameDetails[Suffix]" 
            maxLength="100" type="text"><SPAN style="display: none;" id="ValSpan_NameDetails[Suffix]"></SPAN> 
          </TD></TR></TBODY></TABLE></DIV>
      <DIV id="AddContactNameSimple"><SPAN class="CompanyOnlyField">Company 
      </SPAN>Name <SPAN class="Required">Required</SPAN><BR><INPUT style="width: 365px;" 
      id="Name" class="BoldFormField" tabIndex="1" name="Name" maxLength="100" 
      type="text"><SPAN style="display: none;" id="ValSpan_Name"></SPAN>
      <DIV style="width: 375px; text-align: right;"><SPAN class="ContactOnlyField"><A 
      style="color: rgb(153, 153, 153); font-size: 10px; font-weight: normal;" 
      tabIndex="-1" onclick="AddContactObject.ShowNameDetails();" href="javascript://">Name 
      details</A></SPAN><SPAN class="CompanyOnlyField">						&nbsp;
      					</SPAN></DIV></DIV></TD>
    <TD vAlign="top"></TD></TR>
  <TR>
    <TD vAlign="top" width="460">				Email<BR>
      <DIV style="float: left;" id="EmailFields"><SPAN id="Email_0"><INPUT 
      style="width: 260px;" id="Email[0][Text]" onchange='AddContactObject.CheckDuplicateIndex("email", 0, this)' 
      class="BoldFormField" tabIndex="2" name="Email[0][Text]" maxLength="100" 
      type="text"><SPAN style="display: none;" 
      id="ValSpan_Email[0][Text]"></SPAN> <SELECT style="width: 100px;" id="Email[0][Type]" 
      class="BoldFormField" tabIndex="2" name="Email[0][Type]"><OPTION 
        selected="" value="Work">Work</OPTION><OPTION 
        value="Personal">Personal</OPTION><OPTION 
      value="Other">Other</OPTION></SELECT><A class="IconSprite IconSprite-remove" 
      tabIndex="-1" onclick='AddContactObject.RemoveField("Email", 0)' href="javascript://"></A><BR>
      <DIV style="text-align: left; font-size: 13px; font-weight: normal; display: none;" 
      id="AddContactDuplicateWarning_email_0" class="Warning DuplicateEmailWarning"></DIV></SPAN>
      <DIV style="padding-right: 18px;" align="right"><A class="AddContactExtraField NoUnderline" 
      tabIndex="-1" onclick='AddContactObject.AddField("Email", AddContactObject.EmailCount);' 
      href="javascript://">Add another email address</A></DIV></DIV><BR><BR></TD>
    <TD vAlign="top">
      <DIV class="ContactOnlyField">					Company Name<BR><INPUT style="width: 365px;" 
      id="CompanyName" class="BoldFormField AutoComplete" tabIndex="4" name="CompanyName" 
      maxLength="100" type="text" AutoCompleteType="Company" 
      autocomplete="off"><SPAN style="display: none;" 
      id="ValSpan_CompanyName"></SPAN></DIV>
      <DIV class="CompanyOnlyField">					Industry<BR><INPUT style="width: 365px;" 
      id="Industry" class="BoldFormField" tabIndex="4" name="Industry" 
      maxLength="100" type="text"><SPAN style="display: none;" id="ValSpan_Industry"></SPAN></DIV></TD></TR>
  <TR>
    <TD vAlign="top">				Phone<BR>
      <DIV style="float: left;" id="PhoneFields"><SPAN id="Phone_0"><INPUT 
      style="width: 260px;" id="Phone[0][Text]" onchange='AddContactObject.CheckDuplicateIndex("phone", 0, this)' 
      class="BoldFormField" tabIndex="3" name="Phone[0][Text]" maxLength="100" 
      type="text"><SPAN style="display: none;" 
      id="ValSpan_Phone[0][Text]"></SPAN> <SELECT style="width: 100px;" id="Phone[0][Type]" 
      class="BoldFormField" tabIndex="3" name="Phone[0][Type]"><OPTION 
        selected="" value="Work">Work</OPTION><OPTION 
        value="Mobile">Mobile</OPTION><OPTION value="Home">Home</OPTION><OPTION 
        value="Fax">Fax</OPTION><OPTION value="Other">Other</OPTION></SELECT><A 
      class="IconSprite IconSprite-remove" tabIndex="-1" onclick='AddContactObject.RemoveField("Phone", 0)' 
      href="javascript://"></A><BR>
      <DIV style="text-align: left; font-size: 13px; font-weight: normal; display: none;" 
      id="AddContactDuplicateWarning_phone_0" class="Warning DuplicateEmailWarning"></DIV></SPAN>
      <DIV style="padding-right: 18px;" align="right"><A class="AddContactExtraField NoUnderline" 
      tabIndex="-1" onclick='AddContactObject.AddField("Phone", AddContactObject.PhoneCount);' 
      href="javascript://">Add another phone number</A></DIV></DIV><BR><BR></TD>
    <TD vAlign="top">
      <DIV class="ContactOnlyField">					Title<BR><INPUT style="width: 365px;" 
      id="Title" class="BoldFormField" tabIndex="5" name="Title" maxLength="100" 
      type="text"><SPAN style="display: none;" id="ValSpan_Title"></SPAN></DIV>
      <DIV class="CompanyOnlyField">					# of Employees<BR><INPUT style="width: 365px;" 
      id="NumEmployees" class="BoldFormField" tabIndex="4" name="NumEmployees" 
      maxLength="100" type="text"><SPAN style="display: none;" id="ValSpan_NumEmployees"></SPAN></DIV></TD></TR>
  <TR>
    <TD style="border-bottom-color: rgb(204, 204, 204); border-bottom-width: 1px; border-bottom-style: solid;" 
    colSpan="2">				&nbsp;			</TD></TR>
  <TR>
    <TD vAlign="top"><BR>
      <DIV id="ShowFieldLink_0"><A style="color: rgb(153, 153, 153); font-weight: bold;" 
      onfocus="AddContactObject.ShowCollapsedField(0);" onclick="AddContactObject.ShowCollapsedField(0);" 
      href="javascript://">Add an Address</A><BR></DIV>
      <DIV style="display: none;" id="ExpandedField_0">				Address<BR>
      <DIV style="width: 397px; float: left;" id="AddressFields">
      <DIV id="Address_0">
      <DIV style="float: right;"><SELECT style="width: 100px;" id="Address[0][Type]" 
      class="BoldFormField" tabIndex="7" name="Address[0][Type]"><OPTION 
        selected="" value="Work">Work</OPTION><OPTION 
        value="Billing">Billing</OPTION><OPTION 
        value="Shipping">Shipping</OPTION><OPTION 
        value="Home">Home</OPTION><OPTION value="Other">Other</OPTION></SELECT><A 
      class="IconSprite IconSprite-remove" tabIndex="-1" onclick='AddContactObject.RemoveField("Address", 0)' 
      href="javascript://"></A><BR></DIV><TEXTAREA style="width: 262px; height: 35px;" id="Address[0][Street]" class="BoldFormField" tabIndex="6" cols="40" rows="5" name="Address[0][Street]"></TEXTAREA> 
      <INPUT style="width: 120px;" id="Address[0][City]" class="BoldFormField" 
      name="Address[0][City]" maxLength="100" type="text"><SPAN style="display: none;" 
      id="ValSpan_Address[0][City]"></SPAN> <INPUT style="width: 45px;" id="Address[0][State]" 
      class="BoldFormField" name="Address[0][State]" maxLength="100" 
      type="text"><SPAN style="display: none;" 
      id="ValSpan_Address[0][State]"></SPAN> <INPUT style="width: 61px;" id="Address[0][Zip]" 
      class="BoldFormField" name="Address[0][Zip]" maxLength="100" 
      type="text"><SPAN style="display: none;" 
      id="ValSpan_Address[0][Zip]"></SPAN> <BR><INPUT style="width: 261px;" id="Address[0][Country]" 
      class="BoldFormField" name="Address[0][Country]" maxLength="200" type="text"><SPAN 
      style="display: none;" id="ValSpan_Address[0][Country]"></SPAN> <BR></DIV>
      <DIV style="padding-right: 122px;" align="right"><A class="AddContactExtraField NoUnderline" 
      tabIndex="-1" onclick='AddContactObject.AddField("Address", AddContactObject.AddressCount);' 
      href="javascript://">Add another address</A></DIV></DIV><BR style="clear: both;"></DIV><BR>
      <DIV id="ShowFieldLink_1"><A style="color: rgb(153, 153, 153); font-weight: bold;" 
      onfocus="AddContactObject.ShowCollapsedField(1);" onclick="AddContactObject.ShowCollapsedField(1);" 
      href="javascript://">Add Background Info</A><BR></DIV>
      <DIV style="display: none;" id="ExpandedField_1">				Background Info<BR><TEXTAREA style="width: 365px; height: 70px; font-size: 12px; font-weight: normal;" id="BackgroundInfo" class="BoldFormField" cols="40" rows="3" name="BackgroundInfo"></TEXTAREA></DIV><BR></TD>
    <TD vAlign="top"><BR>
      <DIV id="ShowFieldLink_2"><A style="color: rgb(153, 153, 153); font-weight: bold;" 
      onfocus="AddContactObject.ShowCollapsedField(2);" onclick="AddContactObject.ShowCollapsedField(2);" 
      href="javascript://">Add a Website</A><BR></DIV>
      <DIV style="display: none;" id="ExpandedField_2">				Website<BR>
      <DIV style="float: left;" id="WebsiteFields"><SPAN id="Website_0"><INPUT 
      style="width: 365px;" id="Website[0][Text]" class="BoldFormField" name="Website[0][Text]" 
      maxLength="100" type="text"><SPAN style="display: none;" id="ValSpan_Website[0][Text]"></SPAN> 
      <A class="IconSprite IconSprite-remove" tabIndex="-1" onclick='AddContactObject.RemoveField("Website", 0)' 
      href="javascript://"></A><BR></SPAN>
      <DIV style="padding-right: 18px;" align="right"><A class="AddContactExtraField NoUnderline" 
      tabIndex="-1" onclick='AddContactObject.AddField("Website", AddContactObject.WebsiteCount);' 
      href="javascript://">Add another website</A></DIV></DIV><BR style="clear: both;"></DIV><BR>
      <DIV id="ShowFieldLink_3"><A style="color: rgb(153, 153, 153); font-weight: bold;" 
      onfocus="AddContactObject.ShowCollapsedField(3);" onclick="AddContactObject.ShowCollapsedField(3);" 
      href="javascript://">Add a Birthday</A><BR></DIV>
      <DIV style="display: none;" id="ExpandedField_3">				Birthday<BR><INPUT 
      style="width: 365px;" id="Birthday" class="BoldFormField" name="Birthday" 
      maxLength="100" type="text"><SPAN style="display: none;" id="ValSpan_Birthday"></SPAN></DIV><BR></TD></TR>
  <TR id="AddContactPipelineTags">
    <TD style="padding: 15px 0px; border-top-color: rgb(204, 204, 204); border-bottom-color: rgb(204, 204, 204); border-top-width: 1px; border-bottom-width: 1px; border-top-style: solid; border-bottom-style: solid;" 
    colSpan="2">
      <DIV class="Tag" 
      onclick="AddContactObject.ShowOpportunityOptions(47557);"><SPAN class="IconSprite IconSprite-money"></SPAN> 
      Attach a Lead</DIV>
      <DIV class="Tag" 
      onclick="AddContactObject.ShowOpportunityOptions(47560);"><SPAN class="IconSprite IconSprite-briefcase"></SPAN> 
      Attach a bills</DIV></TD></TR></TBODY></TABLE></DIV></DIV>
<DIV style="display: none;" class="AddOpportunityToNewContact_47557 AddOpportunityPipelineWrapper">
<DIV style="color: rgb(102, 102, 102); padding-left: 20px; font-size: 16px; border-top-color: rgb(204, 204, 204); border-top-width: 1px; border-top-style: solid; position: relative;" 
class="ContentHeader Big ContactDialog_ContactForm ContactDialogPipelineHeader"><SPAN 
class="IconSprite IconSprite-money"></SPAN> Lead Information			
<DIV style="top: 0px; right: 0px; font-size: 12px; font-weight: normal; margin-right: 50px; position: absolute; text-shadow: none;"><A 
onclick="AddContactObject.CancelOpportunityOptions(47557);" 
href="javascript://">Remove this Lead</A></DIV></DIV></DIV>
<DIV style="display: none;" class="AddOpportunityToNewContact_47560 AddOpportunityPipelineWrapper">
<DIV style="color: rgb(102, 102, 102); padding-left: 20px; font-size: 16px; border-top-color: rgb(204, 204, 204); border-top-width: 1px; border-top-style: solid; position: relative;" 
class="ContentHeader Big ContactDialog_ContactForm ContactDialogPipelineHeader"><SPAN 
class="IconSprite IconSprite-briefcase"></SPAN> bills Information			
<DIV style="top: 0px; right: 0px; font-size: 12px; font-weight: normal; margin-right: 50px; position: absolute; text-shadow: none;"><A 
onclick="AddContactObject.CancelOpportunityOptions(47560);" 
href="javascript://">Remove this bills</A></DIV></DIV></DIV>
<DIV style="padding: 20px;" id="AddContactStatusUpdate">
<TABLE cellSpacing="0" cellPadding="0">
  <TBODY>
  <TR>
    <TD vAlign="top" width="460">
      <DIV style="display: none;" id="AddContactStatusOptions_47557" class="AddContactStatusOptions">
      <DIV class="BoldDarkGray">				Status			</DIV><SELECT style="width: 380px;" 
      id="AddContactStatus_47557" onchange='AddContactObject.ProcessNewStatus("#AddContactStatus_47557");' 
      class="BoldFormField" name="AddContactStatus_47557"><OPTION value="196578">Prospect</OPTION><OPTION 
        value="196579">Qualified Lead</OPTION><OPTION value="196580">Sale 
        Completed (Closed)</OPTION><OPTION value="196581">Sale Lost 
        (Closed)</OPTION></SELECT></DIV>
      <DIV style="display: none;" id="AddContactStatusOptions_47560" class="AddContactStatusOptions">
      <DIV class="BoldDarkGray">				Status			</DIV><SELECT style="width: 380px;" 
      id="AddContactStatus_47560" onchange='AddContactObject.ProcessNewStatus("#AddContactStatus_47560");' 
      class="BoldFormField" name="AddContactStatus_47560"><OPTION value="196618">Active</OPTION><OPTION 
        value="196620">启动</OPTION><OPTION value="196621">计划</OPTION><OPTION 
        value="196622">执行</OPTION><OPTION value="196623">监控</OPTION><OPTION 
        value="196624">收尾</OPTION><OPTION value="196619">Closed 
      (Closed)</OPTION></SELECT></DIV></TD>
    <TD>
      <DIV class="BoldDarkGray">			Priority		</DIV><SELECT style="width: 380px;" 
      id="AddContactPriority" class="BoldFormField" name="Priority"><OPTION 
        value="">No Priority Selected</OPTION><OPTION value="1">Low 
        Priority</OPTION><OPTION value="2">Medium Priority</OPTION><OPTION 
        value="3">High Priority</OPTION></SELECT></TD></TR></TBODY></TABLE>
<DIV style="font-size: 13px; margin-top: 15px;" id="AddContactNoteLink"><A 
style="top: -1px; position: relative;" class="IconSprite IconSprite-note" 
onclick="AddContactObject.ShowNoteField();" href="javascript://">Add a 
note</A><A style="padding-left: 4px;" onclick="AddContactObject.ShowNoteField();" 
href="javascript://">Add a note</A></DIV>
<DIV style="display: none;" id="AddContactNoteDiv">
<DIV style="margin-top: 12px;" class="BoldDarkGray">			Note		</DIV>
<DIV><TEXTAREA style="width: 365px; height: 50px; font-size: 12px; font-weight: normal;" id="AddContactStatusNote" class="BoldFormField" name="StatusNote"></TEXTAREA></DIV></DIV>
<DIV style="font-size: 13px; margin-top: 15px;" id="AddContactReminderLink"><A 
style="top: -1px; position: relative;" class="IconSprite IconSprite-checkbox_tick" 
onclick="AddContactObject.ShowReminderOptions();" href="javascript://">Add a 
task to follow up</A><A style="padding-left: 4px;" onclick="AddContactObject.ShowReminderOptions();" 
href="javascript://">Add a task to follow up</A></DIV>
<DIV style="padding-top: 10px; margin-top: 15px; border-top-color: rgb(204, 204, 204); border-top-width: 1px; border-top-style: solid; display: none;" 
id="AddContactReminderDiv">
<TABLE cellSpacing="0" cellPadding="0" width="100%">
  <TBODY>
  <TR>
    <TD vAlign="top" width="460">
      <DIV class="BoldDarkGray">						Task Name						<SPAN 
      class="Required">Required</SPAN></DIV>
      <DIV><INPUT style="width: 365px;" id="AddContactReminderDescription" 
      class="BoldFormField" name="TodoName" type="text"></DIV><BR>
      <DIV style="font-size: 13px;"><A style="top: -1px; position: relative;" 
      class="IconSprite IconSprite-bin" onclick="AddContactObject.HideReminderOptions();" 
      href="javascript://">Remove this task</A><A style="padding-left: 4px;" 
      onclick="AddContactObject.HideReminderOptions();" 
      href="javascript://">Remove this task</A></DIV></TD>
    <TD>
      <DIV class="BoldDarkGray">						Due Date					</DIV>
      <DIV style="font-size: 10px;" 
  id="AddContactReminderDate"></DIV></TD></TR></TBODY></TABLE></DIV></DIV>
<DIV style="padding: 20px;"><INPUT id="CreateContactButton" class="GreenSubmit" value="Create Contact" type="submit"><INPUT 
name="FormSubmit" value="true" type="Hidden"><INPUT id="AddContactPipelineId" 
name="PipelineId" value="0" type="hidden"><INPUT id="AddContactReminderSet" 
name="ReminderSet" value="0" type="hidden"><INPUT id="AddContactNoteSet" name="NoteSet" 
value="0" type="hidden"><INPUT id="AddContactSelectedDate" name="SelectedDate" 
type="hidden"><INPUT id="AddOpportunity_OpportunityId" name="OpportunityId" 
type="hidden"><INPUT id="AddOpportunity_PipelineId" name="AttachPipelineId" 
type="hidden"><INPUT id="AddOpportunity_ContactId" name="ContactId" type="hidden"><INPUT 
id="AddOpportunity_IsCompanyFeed" name="IsCompanyFeed" type="hidden"></DIV>
<DIV style="display: none;"><SPAN id="MultiForm_Email"><SPAN 
id="Email_xxx"><INPUT style="width: 260px;" id="Email[xxx][Text]" onchange='AddContactObject.CheckDuplicateIndex("email", xxx, this)' 
class="BoldFormField" tabIndex="2" name="Email[xxx][Text]" maxLength="100" type="text"><SPAN 
style="display: none;" id="ValSpan_Email[xxx][Text]"></SPAN> <SELECT style="width: 100px;" 
id="Email[xxx][Type]" class="BoldFormField" tabIndex="2" 
  name="Email[xxx][Type]"><OPTION selected="" value="Work">Work</OPTION><OPTION 
  value="Personal">Personal</OPTION><OPTION 
value="Other">Other</OPTION></SELECT><A class="IconSprite IconSprite-remove" 
tabIndex="-1" onclick='AddContactObject.RemoveField("Email", xxx)' href="javascript://"></A><BR>
<DIV style="text-align: left; font-size: 13px; font-weight: normal; display: none;" 
id="AddContactDuplicateWarning_email_xxx" 
class="Warning DuplicateEmailWarning"></DIV></SPAN></SPAN><SPAN id="MultiForm_Phone"><SPAN 
id="Phone_xxx"><INPUT style="width: 260px;" id="Phone[xxx][Text]" onchange='AddContactObject.CheckDuplicateIndex("phone", xxx, this)' 
class="BoldFormField" tabIndex="3" name="Phone[xxx][Text]" maxLength="100" type="text"><SPAN 
style="display: none;" id="ValSpan_Phone[xxx][Text]"></SPAN> <SELECT style="width: 100px;" 
id="Phone[xxx][Type]" class="BoldFormField" tabIndex="3" 
  name="Phone[xxx][Type]"><OPTION selected="" value="Work">Work</OPTION><OPTION 
  value="Mobile">Mobile</OPTION><OPTION value="Home">Home</OPTION><OPTION value="Fax">Fax</OPTION><OPTION 
  value="Other">Other</OPTION></SELECT><A class="IconSprite IconSprite-remove" 
tabIndex="-1" onclick='AddContactObject.RemoveField("Phone", xxx)' href="javascript://"></A><BR>
<DIV style="text-align: left; font-size: 13px; font-weight: normal; display: none;" 
id="AddContactDuplicateWarning_phone_xxx" 
class="Warning DuplicateEmailWarning"></DIV></SPAN></SPAN><SPAN id="MultiForm_Website"><SPAN 
id="Website_xxx"><INPUT style="width: 365px;" id="Website[xxx][Text]" class="BoldFormField" 
name="Website[xxx][Text]" maxLength="100" type="text"><SPAN style="display: none;" 
id="ValSpan_Website[xxx][Text]"></SPAN> <A class="IconSprite IconSprite-remove" 
tabIndex="-1" onclick='AddContactObject.RemoveField("Website", xxx)' href="javascript://"></A><BR></SPAN></SPAN><SPAN 
id="MultiForm_Address">
<DIV id="Address_xxx"><BR>
<DIV style="float: right;"><SELECT style="width: 100px;" id="Address[xxx][Type]" 
class="BoldFormField" tabIndex="7" name="Address[xxx][Type]"><OPTION selected="" 
  value="Work">Work</OPTION><OPTION value="Billing">Billing</OPTION><OPTION 
  value="Shipping">Shipping</OPTION><OPTION value="Home">Home</OPTION><OPTION 
  value="Other">Other</OPTION></SELECT><A class="IconSprite IconSprite-remove" 
tabIndex="-1" onclick='AddContactObject.RemoveField("Address", xxx)' href="javascript://"></A><BR></DIV><TEXTAREA style="width: 262px; height: 35px;" id="Address[xxx][Street]" class="BoldFormField" tabIndex="6" cols="40" rows="5" name="Address[xxx][Street]"></TEXTAREA> 
<INPUT style="width: 120px;" id="Address[xxx][City]" class="BoldFormField" name="Address[xxx][City]" 
maxLength="100" type="text"><SPAN style="display: none;" id="ValSpan_Address[xxx][City]"></SPAN> 
<INPUT style="width: 45px;" id="Address[xxx][State]" class="BoldFormField" name="Address[xxx][State]" 
maxLength="100" type="text"><SPAN style="display: none;" id="ValSpan_Address[xxx][State]"></SPAN> 
<INPUT style="width: 61px;" id="Address[xxx][Zip]" class="BoldFormField" name="Address[xxx][Zip]" 
maxLength="100" type="text"><SPAN style="display: none;" id="ValSpan_Address[xxx][Zip]"></SPAN> 
<BR><INPUT style="width: 261px;" id="Address[xxx][Country]" class="BoldFormField" 
name="Address[xxx][Country]" maxLength="200" type="text"><SPAN style="display: none;" 
id="ValSpan_Address[xxx][Country]"></SPAN> <BR></DIV></SPAN></DIV></DIV></FORM>
<DIV id="OpportunityActivityWrapper">
<DIV style="margin-top: 20px; border-top-color: rgb(204, 204, 204); border-top-width: 1px; border-top-style: solid;" 
class="ContentHeader Big">			Activity Feed for this <SPAN class="UpdateOpportunityPipelineName"></SPAN></DIV>
<DIV style="overflow-x: hidden; overflow-y: auto; max-height: 400px;" id="UpdateOpportunityActivityDiv"></DIV>
<DIV class="DialogFooter" align="right"><A style="top: -1px; position: relative;" 
class="IconSprite IconSprite-bin" onclick="OpportunityObject.DeleteOpportunity();" 
href="javascript://">Delete this <SPAN 
class="DeleteOpportunityName"></SPAN></A><A style="padding-left: 4px;" onclick="OpportunityObject.DeleteOpportunity();" 
href="javascript://">Delete this <SPAN 
class="DeleteOpportunityName"></SPAN></A></DIV></DIV></DIV></DIV></DIV>
<DIV id="AJAXPAGE_js__file" class="AJAXPageTemplate">
<STYLE>
#ContactFileInputUploader {
		color:white;
		text-decoration:none;
		font-size:17px;
		font-weight:bold;
		text-shadow: 1px 1px 1px #000;
		font-family: 'Droid Serif', serif;
		letter-spacing:1px;
		line-height:34px;
		border-radius: 5px;
		white-space:nowrap;
		width:200px;
		height:50px;
		border:1px solid #175d00;
		cursor:pointer;
		background-image:url(/i/app/select_file.png);
		/*background-image:url(/i/app/select_files.png);*/
		background-color: #3f8521;
		background-repeat:no-repeat;
		background-position: center center;
}

#ContactFileInputUploader:hover{
		background-color: #175d00;
}

</STYLE>

<SCRIPT type="text/javascript">

var ContactFileObject = new ContactFileClass();	

$(function(){
	//ContactFileObject.OpenDialog();
});

function ContactFileClass(){
	this.ContactId;
	this.FileId = 0;
	
	this.OpenDialog = function(ContactId, FileId){
		this.ContactId = ContactId;		
		
		if(typeof FileId !== "undefined")
			this.FileId = FileId;
		else
			this.FileId = 0;
		
		if(swfobject.getFlashPlayerVersion().major == 0){
			$('#SelectNewFileUpdate').remove();
			$('#ContactUploadFileDialogWrapper').html("<iframe src='/ajax/app/files/iframe.php?ContactId="+ContactId+"&FileId="+FileId+"' width='400' height='200' style='border:0; '></iframe>");
			DialogFromSource("ContactUploadNewFile", 500);
			//Dialog("<div class='DialogHeader'>Please Install Flash</div><div style='padding:20px;' class='BoldDarkGray'>Sorry, but the file uploader requires Adobe Flash to be installed on your computer. <a href='http://get.adobe.com/flashplayer/' target='_blank'>Please click here to install flash</a>.<br /><br />Once you've installed it, <a href='javascript://' onclick='window.location.reload();'>Reload the page</a> and try uploading again.</div>");
			return;
		}
		
		
		


		//alert('/ajax/app/files/upload_files.php?ContactId='+ContactId+(FileId > 0 ? "&FileId="+FileId : ""));
		
		//We need to re-instantiate this each time so the FileId is right
		$('#ContactFileInput').remove();
		$('#ContactUploadFileDialogWrapper').html("<input type='file' id='ContactFileInput' name='file_upload'/>");
		
		if(this.FileId == 0)
			$('#SelectNewFileUpdate').hide();
		else
			$('#SelectNewFileUpdate').show();
		
		$('#ContactFileInput').uploadify({
			'uploader'  : '/include/uploadify/uploadify.swf',
			'script'    : '/ajax/app/files/upload_files.php?ContactId='+ContactId,
			'cancelImg' : '/include/uploadify/cancel.png',
			'folder'    : '/ajax/app/files/tempfiles/',
			'expressInstall' : '/include/uploadify/expressInstall.swf',
			'auto'      : true,
			'wmode'       : 'transparent',
			'hideButton'  : true,
			'multi': true,
			'sizeLimit'   : 52428800,
			'width' : "200",
			'height': '50',
			'scriptData': { 'session': '2hnfjfimovh2l8pp0ue7fcnjl4', 'FileId':this.FileId},
			'simUploadLimit' : 1, //only one file will upload at a time so it's easier to handle the back-end
			'onAllComplete' : function(event, data){
				ContactFileObject.HandleResponse();
			},
			"onError":function(event,ID,fileObj,errorObj) {
				if(errorObj.type == 'File Size'){
					alert("Error uploading "+fileObj.name+" - files must be less than 50 megabytes");
				}
				else{
					 alert(errorObj.type + ' Error: ' + errorObj.info+". If you keep getting this error, click the \"Contact us\" link at the top of the page for help.");
				}
			}
		});
		this.SWFLoaded = true;

		
		DialogFromSource("ContactUploadNewFile", 500);
		RepositionDialogs();
		
	}
	
	this.HandleResponse = function(){
		 if(this.FileId == 0){
			GrayOutArea('#ContactUploadFileDialogWrapper', true);
			$.post('/appinclude/action/files/refresh_file_list.php', {ContactId:this.ContactId}, function(Data){
				InsertMarkupFromAJAX(Data);
				CloseDialogFromSource('ContactUploadNewFile');
			});
		}else{
			CloseDialogFromSource('ContactUploadNewFile');
			setTimeout("ContactFileObject.ViewFile("+this.FileId+", "+this.ContactId+", true)", 50);
		}
	}
	
	this.ViewFile = function(ThisFileId, ContactId, IsUpdated){
		this.ContactId = ContactId;
		this.FileId = ThisFileId;
		var DialogId = Dialog("<div id='ContactViewFileDialog'><div style='padding:50px;text-align:center;'><img src='style/default/images/main/loading.gif' /></div></div>",675);
		
		$.post("/appinclude/action/files/view.php"+(IsUpdated == true ? "?FileUpdated=true&ContactId="+ContactId : ""), {FileId:ThisFileId}, function(Data){
			InsertMarkupFromAJAX(Data);
			RepositionDialog(DialogId);
			
			$('#ContactFileRenameField').bind("keydown", "return", function(){
				ContactFileObject.SaveNewName();
			});
			
		});
		
	}
	
	this.ConfirmDelete = function(FileId){
		alert("this isn't working yet");
	}
	
	this.SaveNewName = function(){
		if($('#ContactFileRenameField').val() == ''){
			alert("Please enter a name");
			return;
		}
		
		$('#ContactFileDisplayName').html($('#ContactFileRenameField').val());
		$('#ContactFileRenameWrapper').hide();
		$('#ContactFileDisplayNameWrapper').fadeIn('slow');
		
		$.post("/appinclude/action/files/rename.php", {FileId:this.FileId, NewName:$('#ContactFileRenameField').val()}, function(Data){
			InsertMarkupFromAJAX(Data);
		});
	}
	
	this.UpdateFile = function(){
		CloseDialogs();
		this.OpenDialog(this.ContactId, this.FileId);
	}
	
	this.ShowFileUploadDialog = function(){
		Dialog("<div class='DialogHeader'>Uploading...</div><div style='padding:40px;' align='center'><img src='style/default/images/main/loading.gif' /></div>");
	}
	
	this.DeleteFile = function(ThisFileId){
		GrayOutArea('.ViewFileDialogContent');
		var HasVersions = $('[id^="FileVersionRow_"]').length>0;
		$('.ViewFileDialogContent').append("<div class='DeleteFileConfirmMessage' style='z-index:999999999;position:absolute; background-color:#fff;border:3px solid #3d6aa6;padding:20px'>\
				<div class='BoldGray' style='font-size:18px; padding-bottom:20px'>The file "+(HasVersions ? "and all previous versions have" : "has")+" been deleted</div>\
				<div align='center'><a href='javascript://' onclick='CloseDialogs()' class='GreenButton'>OK</a>\
				<span style='padding:0px 10px'>&nbsp;</span>\
				<a href='javascript://' onclick='ContactFileObject.UndeleteFile("+ThisFileId+")' style='font-size:13px;'>Undo</a>\
				</div>\
				</div>");
		$('.DeleteFileConfirmMessage').css('left',(($('.ViewFileDialogContent').width()-$('.DeleteFileConfirmMessage').width()-40)/2)+'px');
		$('.DeleteFileConfirmMessage').css('top','50px');

		$.post("/appinclude/action/files/delete_version.php", {FileId:ThisFileId,ContactId:this.ContactId}, function(Data){
			InsertMarkupFromAJAX(Data);
		});
	}

	this.DeleteVersion = function(ThisFileId){
		$('#FileVersionRow_'+ThisFileId).after("<tr class='FileVersionRow_Added'> <td colspan='99' align='center' style='background-color:#ddd;'>This version has been deleted.\
				<a href='javascript://' onclick='ContactFileObject.UndeleteVersion("+ThisFileId+")'>Undo</a></td></tr>")
		$('#FileVersionRow_'+ThisFileId).hide();
		
		$.post("/appinclude/action/files/delete_version.php", {FileId:ThisFileId,ContactId:this.ContactId}, function(Data){
			InsertMarkupFromAJAX(Data);
		});
	}

	this.UndeleteVersion = function(ThisFileId){
		$('#FileVersionRow_'+ThisFileId).show();
		$('.FileVersionRow_Added').remove();

		$.post("/appinclude/action/files/undelete_version.php", {FileId:ThisFileId,ContactId:this.ContactId}, function(Data){
			InsertMarkupFromAJAX(Data);
		});
	}

	this.UndeleteFile = function(ThisFileId){
		$('.DeleteFileConfirmMessage').remove();
		EndGrayOutArea();

		$.post("/appinclude/action/files/undelete_version.php", {FileId:ThisFileId,ContactId:this.ContactId}, function(Data){
			InsertMarkupFromAJAX(Data);
		});
	}
}

</SCRIPT>

<DIV style="display: none;" id="DialogWrapper_ContactUploadNewFile">
<DIV id="DialogSource_ContactUploadNewFile">
<DIV class="DialogHeader NewFileType">		Upload File	</DIV>
<DIV style="margin: 20px 10px; color: rgb(153, 153, 153); font-size: 14px; font-weight: bold;" 
id="SelectNewFileUpdate" align="center">		Select the new version from your 
computer.	</DIV>
<DIV style="padding: 20px 0px;" id="ContactUploadFileDialogWrapper" align="center"><INPUT 
id="ContactFileInput" name="file_upload" type="file"></DIV>
<DIV style="padding: 10px; color: rgb(153, 153, 153); font-size: 12px;" class="DialogFooter" 
align="center">		You're using 0.2% of your 10 GB storage limit	</DIV>
</DIV></DIV></DIV>
<DIV id="AJAXPAGE_js__perm_sidebar" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
//ASDFASDFASDF
$(function(){
	var Sidebar = $('#PermSidebar');
	$window    = $(window),
	topPadding = 0;
	SidebarOffset = $('.HeaderWrapperDiv').height()+$('.NavigationBar').height()+21;
	
	$window.scroll(function() {
		PermSidebarObject.ResizePermSidebar();
	});
	
	
	
	Sidebar.bind("mousewheel", function(event, delta, deltaX, deltaY){
		PermSidebarScroll = Math.max(0, PermSidebarScroll - delta * 150);
		Sidebar.stop();
		Sidebar.animate({scrollTop : PermSidebarScroll},'slow', function(){
			PermSidebarScroll = Sidebar.scrollTop();
		});
		
		//$('.PermSidebarTitle').animate({top: PermSidebarScroll}, 'slow', function(){});
		
		if(delta > 0){
			//we're scrolling up
			if(Sidebar.scrollTop() < 10)
				return true;
			else
				return false;
		}
		else{
			//scroll down
			//alert(Sidebar.scrollHeight()+" - "+Sidebar.scrollTop()+" == "+Sidebar.outerHeight());
			if(Sidebar[0].scrollHeight - Sidebar.scrollTop() == Sidebar.outerHeight()){
				return true;
			}
			else{
				return false;
			}
		}
		return false;
	});
});

var PermSidebarObject = new PermSidebarClass();	

function PermSidebarClass(){
	this.ReturnURL = '';
	
	this.ResizePermSidebar = function(){
		var $sidebar   = $("#PermSidebar"),
		$window    = $(window),
		topPadding = 0;
		SidebarOffset = $('.HeaderWrapperDiv').height()+$('.NavigationBar').height()+21;
		
		$('.TopPageNotification').each(function(){
			SidebarOffset += $(this).outerHeight();
		});
		
		if ($window.scrollTop() < SidebarOffset) {
			//The sidebar is below the nav stuff at the top
			var ScrollTop = $window.scrollTop();
			$sidebar.css('top', SidebarOffset - ScrollTop+"px");
			$('.PermSidebarTitle').css('top', SidebarOffset - ScrollTop+"px");
			$("#PermSidebar").height($(window).height() - (SidebarOffset - ScrollTop)-50);
		} else if($window.scrollTop()+$window.height() > SidebarOffset + $('#BodyMain').height()){
			//the user scrolled past the bottom of the page
			$sidebar.css('top', "-"+(($window.scrollTop()+$window.height()) - (SidebarOffset + $('#BodyMain').height()))+"px");
			$('.PermSidebarTitle').css('top', "0px");
			$("#PermSidebar").height($(window).height()-50);
		}		
		else {
			//The sidebar is at 100% height and fixed on the screen
			$sidebar.css('top', "0px");
			$('.PermSidebarTitle').css('top', "0px");
			$("#PermSidebar").height($(window).height()-50);
		}
	}
	
	
	
	//Select the right contact on the sidebar and scroll to the correct position
	this.SelectContactOnSidebar = function(){
		var ContactId = ViewContactObject.ContactId;
		$('.PermSidebarSelected').removeClass('PermSidebarSelected');
		if($('.PermSidebarLink_'+ContactId).size() > 0){
			$('.PermSidebarLink_'+ContactId).addClass("PermSidebarSelected");
			$('.PermSidebarLink_'+ContactId).addClass("PermSidebarViewed");
			
			if(!$('#PermSidebar').is(":visible")){
				$('#PermSidebar').show();
				TitleWidth = $('.PermSidebarTitle').width();
				$('.PermSidebarTitle').width(0);
				
				$('#BodyMain').animate({width:$('#BodyMain').width()-250}, 1000, function(){
					ResizeWindow();
				});
				
				$('.PermSidebarTitle').animate({width:TitleWidth}, 1000, function(){});
				
				$('.PermSidebarReturnLink').attr('href', unescape(this.ReturnURL));
			}
			
			var RowPosition = $('.PermSidebarLink_'+ContactId).position();
			var Sidebar = $('#PermSidebar');
			var HalfHeight = Sidebar.height() / 2;
			var CurrentScrollTop = RowPosition.top+$('#PermSidebar').scrollTop();
			
			$('#PermSidebar').stop();
			PermSidebarScroll = CurrentScrollTop-HalfHeight;
			$('#PermSidebar').animate({scrollTop : CurrentScrollTop-HalfHeight},1500, function(){
				PermSidebarScroll = $('#PermSidebar').scrollTop();
			});
		}
	}
	
	this.ContactWasEdited = function(ContactId){
		$('.PermSidebarLink_'+ContactId).append("<div class='PermLinkUpdatedToday'>Updated Today</div>");
	}
	
	this.HidePermSidebar = function(){
		if($('#PermSidebar').is(":visible")){
			$('.PermSidebarTitle').remove();
			$('#PermSidebar').append('<span class="OLD_PERM_SIDEBAR_DATA_PLEASE_DELETE"></span>');
			$('#BodyMain').animate({width:$('#BodyMain').width()+250}, 500, function(){
				if($('.OLD_PERM_SIDEBAR_DATA_PLEASE_DELETE').length > 0){
					$('#PermSidebar').html('');
				}
				$('#PermSidebar').hide();
				ResizeWindow();
			});
			$('.LoadingPageGraphic').animate({width:$('.LoadingPageGraphic').width()+250}, 500, function(){});
		}
		else{
			$('#PermSidebar').html('');
		}
	}
	
	//This is used when contacts are merged
	this.ReplaceRow = function(OldContactId, NewRowHTML){
		$('.PermSidebarLink_'+OldContactId).parent().replaceWith(NewRowHTML);
		//$('.PermSidebarLink_'+OldContactId).remove();
		//$('.PermSidebarLink').unbind();
		ProcessSpecificLink('.PermSidebarLink')
	}

	this.RemoveContactFromSidebar = function(ContactId){
		$('.PermSidebarLink_'+ContactId).remove();
	}
	
	//Get the current URL so we can return to this report
	this.StoreReturnURL = function(){
		var HashPage = window.location.hash.replace("#", "");
		if(HashPage == "") {
			this.ReturnURL = OriginalCurrentPage;
		} else {
			this.ReturnURL = HashPage;
		}
		this.ReturnURL = str_replace("?t=", "?t="+Math.random(), this.ReturnURL);
	}
}

</SCRIPT>
</DIV>
<DIV id="AJAXPAGE_js__reminder" class="AJAXPageTemplate">
<STYLE>
.TodoLink{
	color:#666666;
}

.CheckedTodo{
	text-decoration:line-through;
	color:#aaaaaa;
}

.CheckedTodo:hover{
	text-decoration:line-through;
	color:#aaaaaa;
}

.TodoAgendaLine{
	text-indent:-22px;
	padding-left:22px;
	margin-top:5px;
}

.ReminderSidebarBoxContent{
	padding:3px 5px;
	background-color:#eeeeee;
	border:1px solid #bbbbbb;
	color:#999999;
	
	-moz-border-radius-bottomleft: 6px;
	-webkit-border-bottom-left-radius: 6px;
	border-bottom-left-radius:6px;
	-moz-border-radius-bottomright: 6px;
	-webkit-border-bottom-right-radius: 6px;
	border-bottom-right-radius:6px;
}

.TodoContactInfo{
	padding-left:20px;
	color:#999999;
	font-size:11px;
}
.GrayedOutTodoContactInfo{
	color:#bbbbbb;
	padding-left:20px;
	font-size:11px;
}
.GrayedOutTodoContactInfo a{
	color:#bbbbbb;
}


</STYLE>

<SCRIPT type="text/javascript">

var ReminderObject = new ReminderClass();	

$(function(){	
	CheckedTodoImage = new Image(16,16); 
	CheckedTodoImage.src="/i/app/checkbox_checked.png"; 
	
	HighlightedTodoImage = new Image(16,16); 
	HighlightedTodoImage.src="/i/app/checkbox_tick.png"; 

	$('#QuickCreateReminderName').bind('keydown', 'return', function(){
		ReminderObject.ProcessEnterSubmit();
	});
});

function ReminderClass(){
	this.SelectedDate = "06/17/2013";
	this.EditReminderId = 0;
	this.PageType = "";
	this.ContactId = '';
	this.ContactName = '';
	this.UserId = 0;
	this.Mode = 'add'; //can be add or edit
	
	this.Tomorrow = '06/18/2013';
	this.Today = '06/17/2013';
	
	this.NewReminder = function(Element, DefaultDate){
		//if Element has a ContactName and ContactId set, use that
		if($(Element).attr('ContactId') != null && $(Element).attr('ContactName') != null){
			this.ContactId = $(Element).attr('ContactId');
			this.ContactName = $(Element).attr('ContactName');
			$('.EditReminderHeader').after("<div class='YellowWarning' align='center' style=''>This task will be linked to "+this.ContactName+"</div>")
			
		}
		else{
			this.ContactId = '';
			this.ContactName = '';
		}
		
		this.UserId = 0;
		this.Mode = 'add';
		
		$('.EditReminderButton').hide();
		$('.AddReminderButton').show();
		
		$('.EditReminderHeader').hide();
		$('.AddReminderHeader').show();
		
		$('#QuickCreateReminderSendEmail').attr('checked', true);
		$('#QuickCreateReminderUserId').val(39944);
		
		this.OpenDialog();
		
		if(DefaultDate == null)
			DefaultDate = Date.today()
		else
			DefaultDate = Date.parse(DefaultDate);
		
		SelectedDate = "";
		$('.ReminderDatepicker').datepicker('setDate', DefaultDate);
		this.SelectedDate = DefaultDate.toString("MM/dd/yyyy");
		$('.ReminderNameWarning').hide();
		$('#QuickCreateReminderName').focus();
	}
	
	//this function is called when the user hits the enter key while focused on the task name
	this.ProcessEnterSubmit = function(){
		if(this.Mode == 'edit'){
			this.SaveEditReminder();
		}
		else{
			this.AddReminder();
		}
	}
	
	this.OpenDialog = function(){
		DialogId = Dialog("<div id='QuickCreateReminderDialog' style=''></div>", 420, "ReminderObject.CloseDialog();");
		$('#QuickCreateReminderSourceDiv').appendTo("#QuickCreateReminderDialog");
		RepositionDialog(DialogId, 890);
		
		$('.ReminderDatepicker').datepicker({
			inline: true,
			numberOfMonths:2,
			onSelect:function(datetext, inst){
				ReminderObject.SetSpecificDate(datetext, inst);
			}
		});	
		
		$('.ReminderDatepicker').bind('mouseover', function(){
			$(this).addClass('HighlightedDateRow');
			
		});
		$('.ReminderDatepicker').bind('mouseout', function(){
			$(this).removeClass('HighlightedDateRow');
		});	
		
		$('#QuickCreateReminderName').val('');
		$('.DateWarning').hide();
		$('.ReminderNameWarning').hide();
	}
	
	this.CloseDialog = function(){
		$('#QuickCreateReminderSourceDiv').appendTo("#QuickCreateReminderSourceDivWrapper");
		$('#QuickCreateReminderSourceDiv').find('.YellowWarning').remove();
		CloseDialog('#QuickCreateReminderDialog');
		
	}
	
	this.SetSpecificDate = function(datetext, inst){
		this.SelectedDate = datetext;
		var Today = new Date("06/17/2013");
		
		/*
		if(Today >= new Date(datetext))
			$('.DateWarning').fadeIn('slow');
		else
			$('.DateWarning').hide();
		*/
		
		$('.DisplayDateSummary').html($.datepicker.formatDate('DD, MM d', new Date(datetext)));
		$('.DisplayActualDate').html('');
		$('.DateDropdown').hide();
	}
	
	this.ChooseDate = function(Element){
		this.SelectedDate = $(Element).attr('SelectedDate');
		
		//alert(SelectedDate);
		if(this.SelectedDate != '')
			$('.ReminderDatepicker').datepicker('setDate', new Date(SelectedDate));
		
		$('.DisplayDateSummary').html($(Element).attr('DateSummary'));
		$('.DisplayActualDate').html($(Element).attr('ActualDate'));
		$('.DateDropdown').hide();
		$('.DateWarning').hide();
		//defaultDate
	}
	
	this.AddReminder = function(){
		var ReminderName = $('#QuickCreateReminderName').val();
		
		var SendEmailOption = '0';
		if ($('#QuickCreateReminderSendEmail').is(':checked') && !($('#QuickCreateReminderUserId').val() == 39944 || this.UserId == $('#QuickCreateReminderUserId').val())) {
		  SendEmailOption = '1';
		}
		
		var ThisUserId = $('#QuickCreateReminderUserId').val();
		if(ThisUserId == undefined)
			ThisUserId = 'NULL';
		
		if(ReminderName == ''){
			$('.ReminderNameWarning').fadeIn('slow');
		}
		else{
			$('.ReminderNameWarning').hide();
			
			GrayOutArea('#QuickCreateReminderSourceDiv', true);
			
			$.post('/appinclude/action/reminders/new.php', {Name:ReminderName, ContactId:this.ContactId, Description:'', DueDate:this.SelectedDate,
															UserId:ThisUserId, SendEmail:SendEmailOption}, function(data){
				InsertMarkupFromAJAX(data);
				
				EndGrayOutArea();
				SystemMessage("The task has been saved");
				
				LogAnalyticsEvent("New Task", "Calendar");
				
				ReminderObject.CloseDialog();
				
				try{
					if(CurrentPage.toLowerCase() == '/app/calendar/view'){
						CalendarObject.GetEvents();
					}
				}
				catch(err){	}
			});
		}
	}
	
	this.EditReminder = function(Element){
		EditReminderId = $(Element).attr('ReminderId');
		ContactId = $(Element).attr('ContactId');
		ContactName = $(Element).attr('ContactName');
		ReminderDate = $(Element).attr('ReminderDate');
		ReminderName = $(Element).attr('ReminderName');
		this.UserId = $(Element).attr('UserId');
		this.EditReminderId = EditReminderId;
		this.OpenDialog();
		
		$('#QuickCreateReminderName').val(ReminderName);
		this.SelectedDate = ReminderDate;
		$('.ReminderDatepicker').datepicker('setDate', new Date(ReminderDate));
		
		$('.ReminderDialogWrapper .LinkToContactDiv').hide();
		
		$('.EditReminderButton').show();
		$('.AddReminderButton').hide();
		
		$('.EditReminderHeader').show();
		$('.AddReminderHeader').hide();
		
		$('#QuickCreateReminderSendEmail').attr('checked', true);
		$('#QuickCreateReminderUserId').val(this.UserId);
		
		$('#QuickCreateReminderName').focus();
		
		this.Mode = 'edit';
		
		if(ContactId != ''){
			$('.EditReminderHeader').after("<div class='YellowWarning' align='center' style='margin-bottom:15px;'>This task is linked to <a href='javascript://' onclick='ReminderObject.CloseDialog(); jQuery.history.load(\"/app/View_Contact?ContactId="+ContactId+"\");' id='ReminderContactLink'>"+ContactName+"</a></div>")
			//ProcessSpecificLink('#ReminderContactLink');
		}
	}
	
	this.SaveEditReminder = function(){
		var ReminderName = $('#QuickCreateReminderName').val();
		
		if(ReminderName == ''){
			$('.ReminderNameWarning').fadeIn('slow');
		}
		else{
			var SendEmailOption = '0';
			if ($('#QuickCreateReminderSendEmail').is(':checked') && !($('#QuickCreateReminderUserId').val() == 39944 || this.UserId == $('#QuickCreateReminderUserId').val())) {
			  SendEmailOption = '1';
			}
			
			if($('#QuickCreateReminderUserId').length == 0){
				ThisUserId = 'NULL';
			}
			else{
				var ThisUserId = $('#QuickCreateReminderUserId').val();
				if(ThisUserId == undefined)
					ThisUserId = 'NULL';
			}
			
			$('.ReminderNameWarning').hide();
			GrayOutArea('#QuickCreateReminderSourceDiv', true);
			$.post('/appinclude/action/reminders/edit.php', {ReminderId:EditReminderId, Name:ReminderName, DueDate:this.SelectedDate, UserId:ThisUserId, SendEmail:SendEmailOption }, function(data){
				EndGrayOutArea();
				SystemMessage("Your changes have been saved");
				InsertMarkupFromAJAX(data);
				ReminderObject.CloseDialog();
				
				try{
					if(CurrentPage.toLowerCase() == '/app/calendar/view'){
						CalendarObject.GetEvents();
					}
					
				}
				catch(err){	}
			});
		}
	}
	
	this.DeleteReminder = function(ThisReminderId){
		//if(ReminderPageType != 'Report'){
			
		GrayOutArea('#QuickCreateReminderSourceDiv', true);
		$.post('/appinclude/action/reminders/delete.php', {ReminderId:ThisReminderId}, function(data){
			EndGrayOutArea();
			SystemMessage("The task has been deleted.  <a href='javascript://' onclick='ReminderObject.UndoDeleteReminder("+ThisReminderId+");'>Undo</a>");
			InsertMarkupFromAJAX(data);
			ReminderObject.CloseDialog();
			try{
					if(CurrentPage.toLowerCase() == '/app/calendar/view'){
						CalendarObject.GetEvents();
					}
				}
				catch(err){	}
		});
	}
	
	this.UndoDeleteReminder = function(ThisReminderId){
		$('#ReminderReportRow_'+ThisReminderId).html("<td colspan='9' style='background-color:#bbbbbb; text-align:center; font-weight:bold; padding:10px;'>Loading...</td>");
		$('.SystemMessage').hide();
		
		$.post('/appinclude/action/reminders/undo_delete.php', {ReminderId:ThisReminderId}, function(data){
			$('.SystemMessage').hide();
			
			InsertMarkupFromAJAX(data);
			try{
				if(CurrentPage.toLowerCase() == '/app/reminders/view'){
					LoadPage('/app/Reminders/View');
				}
			}
			catch(err){	}
		});
	}
	
	this.CheckTodo = function(Element){
		var ThisReminderId = $(Element).attr('ReminderId');
		var IsChecked = $(Element).attr('IsChecked');
		
		//remember to update dashboard, sidebar, and contact profiles
		
		if(IsChecked == '1'){
			//This event was already checked
			
			$('.TodoIconBig_'+ThisReminderId).attr('src', '/i/app/checkbox.png');

			$('.TodoLink_'+ThisReminderId).removeClass('CheckedTodo');
			$('.TodoLink_'+ThisReminderId).css('text-decoration', 'none');
			$('.TodoLink_'+ThisReminderId).css('color', '#666');
			$('.TodoIcon_'+ThisReminderId).attr('IsChecked', 0);
			
			$('.TodoContactLinkText_'+ThisReminderId).removeClass('GrayedOutTodoContactInfo');
			
			var NewCheckedVal = 0;
		}
		else{
			//This event wasn't checked yet
			
			$('.TodoIconBig_'+ThisReminderId).attr('src', '/i/app/checkbox_checked.png');

			$('.TodoLink_'+ThisReminderId).addClass('CheckedTodo');
			$('.TodoLink_'+ThisReminderId).css('text-decoration', 'line-through');
			$('.TodoLink_'+ThisReminderId).css('color', '#bbb');
			$('.TodoIcon_'+ThisReminderId).attr('IsChecked', 1);
			
			$('.TodoContactLinkText_'+ThisReminderId).addClass('GrayedOutTodoContactInfo');
			
			var NewCheckedVal = 1;
		}
		
		$.post('/appinclude/action/reminders/complete_todo.php', {ReminderId:ThisReminderId, IsChecked:NewCheckedVal}, function(Data){
			
		});
	}
	
	//This function checks off whatever reminder is currently being edited
	this.CheckCurrentTodo = function(){
		$('.TodoIconBig_'+this.EditReminderId).attr('src', '/i/app/checkbox_checked.png');

		$('.TodoLink_'+this.EditReminderId).addClass('CheckedTodo');
		$('.TodoLink_'+EditReminderId).css('text-decoration', 'line-through');
		$('.TodoLink_'+EditReminderId).css('color', '#bbb');
		$('.TodoIcon_'+this.EditReminderId).attr('IsChecked', 1);
		
		$('.TodoContactLinkText_'+this.EditReminderId).addClass('GrayedOutTodoContactInfo');
		
		$.post('/appinclude/action/reminders/complete_todo.php', {ReminderId:this.EditReminderId, IsChecked:1}, function(Data){		});
		
	}
	
	this.HoverDashboardCheckbox = function(ImageElement, ReminderId){
		if($(ImageElement).attr('src') == '/i/app/checkbox.png'){
			$(ImageElement).attr('src', '/i/app/checkbox_tick.png');
		}
		else{
			//This is already checked and shouldn't have a mouseover
		}
	}
	
	this.EndHoverDashboardCheckbox = function(ImageElement, ReminderId){
		if($(ImageElement).attr('src') == '/i/app/checkbox_tick.png'){
			$(ImageElement).attr('src', '/i/app/checkbox.png');
		}
		else{
			//This is already checked and shouldn't have a mouseover
		}
	}
	
	this.ClearOverdueTodos = function(){
		$('.OverdueTodos').after("<div style='display:none; font-size:11px;' class='YellowWarning OverTodoClearedConfirm' align='center'>Your overdue tasks have been<br />marked as completed. <a href='javascript://' onclick='ReminderObject.UndoClearOverdueTodos();'>Undo</a></div>");
		$('.OverdueTodos').slideUp('slow', function(){
			$('.OverTodoClearedConfirm').slideDown('fast');
		});
		
		$.post('/appinclude/action/reminders/clear_overdue.php', {}, function(Data){
			
		});
		
		
		setTimeout("$('.OverTodoClearedConfirm').fadeOut('slow');", 15000);
	}
	
	this.UndoClearOverdueTodos = function(){
		var ReminderIds = "";
		$('.OverdueTodoItem').each(function(){
			if($(this).attr('IsChecked') == 0)
				ReminderIds += $(this).attr('ReminderId')+',';
		});
		$.post('/appinclude/action/reminders/clear_overdue.php', {Undo:ReminderIds}, function(Data){
			
		});
		
		$('.OverTodoClearedConfirm').remove();
		$('.OverdueTodos').slideDown("fast");
		
	}
	
}

</SCRIPT>

<DIV style="display: none;" id="QuickCreateReminderSourceDivWrapper">
<DIV id="QuickCreateReminderSourceDiv">
<DIV class="DialogHeader AddReminderHeader">Create a new task</DIV>
<DIV class="DialogHeader EditReminderHeader">Edit task</DIV>
<DIV style="padding: 20px;">
<DIV style="color: rgb(153, 153, 153); font-size: 14px; font-weight: bold; z-index: 1;">Task 
description</DIV>
<DIV style="padding: 5px; color: white; font-size: 14px; font-weight: bold; display: none; background-color: rgb(231, 102, 25);" 
class="ReminderNameWarning" align="center">		Please enter a description for your 
task	</DIV>
<DIV style="padding: 0px;"><INPUT style="padding: 5px; width: 365px;" id="QuickCreateReminderName" 
class="BoldFormField" type="text"></DIV>
<DIV style="height: 20px;">&nbsp;</DIV>
<DIV style="color: rgb(153, 153, 153); padding-bottom: 4px; font-size: 14px; font-weight: bold;">Due 
Date</DIV>
<DIV style="font-size: 10px;" class="ReminderDatepicker"></DIV><BR><BR>
<DIV align="center">
<TABLE class="AddReminderButton">
  <TBODY>
  <TR>
    <TD><A class="GreenButton" onclick="ReminderObject.AddReminder();" href="javascript://">Create 
      task</A></TD>
    <TD style="padding-left: 50px;"><A onclick="ReminderObject.CloseDialog()" 
      href="javascript://">Cancel</A></TD></TR></TBODY></TABLE>
<TABLE style="display: none;" class="EditReminderButton">
  <TBODY>
  <TR>
    <TD><A class="GreenButton" onclick="ReminderObject.SaveEditReminder(this)" 
      href="javascript://">Save Changes</A></TD>
    <TD style="padding-left: 20px; font-size: 12px;"><A style="top: -1px; position: relative;" 
      class="IconSprite IconSprite-checkbox_tick" onclick="ReminderObject.CheckCurrentTodo(); ReminderObject.CloseDialog();" 
      href="javascript://">Mark this as completed</A><A style="padding-left: 4px;" 
      onclick="ReminderObject.CheckCurrentTodo(); ReminderObject.CloseDialog();" 
      href="javascript://">Mark this as completed</A><BR><A style="top: -1px; position: relative;" 
      class="IconSprite IconSprite-cross" onclick="ReminderObject.DeleteReminder(EditReminderId);" 
      href="javascript://">Delete this task</A><A style="padding-left: 4px;" 
      onclick="ReminderObject.DeleteReminder(EditReminderId);" href="javascript://">Delete 
      this task</A></TD></TR></TBODY></TABLE></DIV></DIV></DIV></DIV></DIV>
<DIV id="AJAXPAGE_permission_error" class="AJAXPageTemplate">
<DIV class="PageHeader">
<H1>Uh oh, something's wrong</H1></DIV>
<DIV style="padding: 20px; color: rgb(153, 153, 153); font-size: 14px; font-weight: bold;">
	You just tried to perform an action that you don't have permission to perform. 
If you think that	there's a bug with the software, please <A href="https://www.lessannoyingcrm.com/account/contact.php">Contact 
us</A> and tell us	what you were doing before you saw this error.		<BR><BR>	
	We're very sorry about this, and we will work to fix it as quickly as possible 
if you let us know what	happened.		<BR><BR>	-The Less Annoying Team</DIV></DIV>
<DIV id="AJAXPAGE_add_contact" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Add a Contact - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = false;
	TempPageSettings['JSBeforeAJAX'] = 'RedirectAndOpenContactDialog()';
	
	PageSettings["add_contact"] = TempPageSettings;
	
	</SCRIPT>

<SCRIPT type="text/javascript">

function RedirectAndOpenContactDialog(){
	jQuery.history.load('/app/Workspace');
	AddContactObject.NewForm('');
}

</SCRIPT>
</DIV>
<DIV id="AJAXPAGE_list_pipelines" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Pipelines';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = 'PermSidebarObject.HidePermSidebar();LogAnalyticsModule("Reporting");';
	
	PageSettings["list_pipelines"] = TempPageSettings;
	
	</SCRIPT>

<DIV id="ListPipelinesResult"></DIV></DIV>
<DIV id="AJAXPAGE_guide" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Beginner\'s Guide';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = 'PermSidebarObject.HidePermSidebar();LogAnalyticsModule("Beginners Guide");';
	
	PageSettings["guide"] = TempPageSettings;
	
	</SCRIPT>

<STYLE>

.GuideBar_IEsucksWhyIsThisNecessary_Wrapper{
	height:60px;
	border-radius:30px;
	margin-top:15px;
	text-align:left;
	box-shadow: inset 0px 0px 2px 2px #aaa;
	overflow:hidden;
}

.GuideBarWrapper{
	height:60px;
	border-radius:30px;
	text-align:left;
	box-shadow: inset 0px 0px 2px 2px #aaa;
	overflow:hidden;
	
	background: #cccccc;
	background: -moz-linear-gradient(top,  #cccccc 0%, #e5e5e5 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#cccccc), color-stop(100%,#e5e5e5));
	background: -webkit-linear-gradient(top,  #cccccc 0%,#e5e5e5 100%);
	background: -o-linear-gradient(top,  #cccccc 0%,#e5e5e5 100%);
	background: -ms-linear-gradient(top,  #cccccc 0%,#e5e5e5 100%);
	background: linear-gradient(to bottom,  #cccccc 0%,#e5e5e5 100%);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#cccccc', endColorstr='#e5e5e5',GradientType=0 );
}

.GuideBarCompleted{
	height:60px;
	text-align:left;
	-webkit-transition: width 1s ease, height 1s ease;
	transition: width 1s ease, height 1s ease;
	
	background: #3e8421;
	background: -moz-linear-gradient(top,  #3e8421 1%, #36721c 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(1%,#3e8421), color-stop(100%,#36721c));
	background: -webkit-linear-gradient(top,  #3e8421 1%,#36721c 100%);
	background: -o-linear-gradient(top,  #3e8421 1%,#36721c 100%);
	background: -ms-linear-gradient(top,  #3e8421 1%,#36721c 100%);
	background: linear-gradient(to bottom,  #3e8421 1%,#36721c 100%);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#3e8421', endColorstr='#36721c',GradientType=0 );
}

.GuideVideoPreviewImage{
	filter: alpha(opacity=70);
	opacity: 0.7;
}
.GuideVideoPreviewImage:hover{
	filter: alpha(opacity=100);
	opacity: 1.0;
}

</STYLE>

<SCRIPT type="text/javascript">

var GuideObject = new GuideClass();

function GuideClass(){
	
	this.Init = function(){
		this.ActivateNextStep();
	}
	
	this.ActivateNextStep = function(){
		$('.GuideStepWrapper').each(function(){
			if($(this).attr('IsComplete') == 0){
				GuideObject.ActivateStep($(this).attr('UniqueCode'));
				return false;
			}
		});
		LogAnalyticsEvent("Advance begginers guide step", "Beginners Guide");
	}
	
	this.ActivateStep = function(UniqueCode){
		//Hide previously active step
		$('.ActiveGuideStep:visible').each(function(){
			var MainWrapper = $(this).parent();
			if($(MainWrapper).attr('IsComplete') == 0){
				MainWrapper.find('.IncompleteGuideStep').show();
			}
			else{
				MainWrapper.find('.CompleteGuideStep').show();
			}
			$(this).hide();
		});
		
		//show the new active step
		var MainWrapper = $('.GuideStepWrapper_'+UniqueCode);
		
		MainWrapper.find('.CompleteGuideStep, .IncompleteGuideStep').hide();
		MainWrapper.find('.ActiveGuideStep').slideDown('slow');
	}
	
	this.ConfirmCloseGuide = function(){
		Dialog("<div style='padding:20px;'><div class='BoldDarkGray'>If you want to use this guide in the future, you can find it by mousing over the \"Help\" link at the top right of every page.</div><br /><br /><div align='center'><a href='/ajax/app/guide/close_guide.php' class='GreenButton'>Ok</a> <a href='javascript://' onclick='CloseDialogs();' style='margin-left:20px;'>Cancel</a></div></div>");
	}
	
	this.CloseGuide = function(){
		window.location = '/ajax/app/guide/close_guide.php';
	}
	
	this.CompleteStep = function(Code, AjaxEndpoint){
		var MainWrapper = $('.GuideStepWrapper_'+Code);
		MainWrapper.attr('IsComplete', 1);
		MainWrapper.find('.ActiveGuideStep').slideUp('fast', function(){
			$('.GuideStepWrapper_'+Code).find('.CompleteGuideStep').show();
			GuideObject.ActivateNextStep();
		});
		
		$.post(AjaxEndpoint, {UniqueCode:Code}, function(Data){
			InsertMarkupFromAJAX(Data);
		});
	}
	this.SkipStep = function(UniqueCode){
		this.CompleteStep(UniqueCode, "/ajax/app/guide/skip_step.php")
	}
	this.AdvanceStep = function(UniqueCode){
		this.CompleteStep(UniqueCode, "/ajax/app/guide/advance_step.php")
	}
	this.WatchVideo = function(Code, VimeoCode){
		$.post("/ajax/app/guide/video_start.php", {UniqueCode:Code}, function(){});
		VimeoPlayer(VimeoCode, 900, 506, function(){
			$.post("/ajax/app/guide/video_stop.php", {UniqueCode:Code}, function(){});
			CloseDialogs();
			
			
		});
	}
	
	this.UpdatePercentComplete = function(NewPercent){
		$('#NavGuidePercentComplete').html(NewPercent+"% complete");
		$('.GuidePercentComplete').html(NewPercent);
		$('.GuideBarCompleted').css('width', NewPercent+"%");
		//Make sure to use an animation on the main completion meter
	}
	
	this.ShowHiddenSection = function(SectionCount){
		$('.GuideSection_'+SectionCount).slideDown('slow');
		$('.GuideSectionClosed_'+SectionCount).hide();
	}
	
	this.SubmitContactForm = function(){
		if($('#GuideContactName').val() == ""){
			alert("Please enter your name. Thanks!");
			return false;
		}
		
		if($('#GuideContactEmail').val() == "" ){
			alert("Please enter your email address so we know how to reach you.");
			return false;
		}
		
		if($('#GuideContactComment').val() ==""){
			alert("Please enter a question, comment, etc. so we know what you need help with. Thanks!");
			return false;
		}
		
		GrayOutArea('#GuideContactForm', true);
		$.post('/ajax/app/guide/contact.php', {Email:$('#GuideContactEmail').val(), Name:$('#GuideContactName').val(), Comment:$('#GuideContactComment').val()}, function(){
			$('#GuideContactForm').hide();
			$('#GuideContactForm_Confirm').slideDown(1000);
		});
	}
}


</SCRIPT>

<DIV id="GuideResult"></DIV></DIV>
<DIV id="AJAXPAGE_workspace" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Workspace - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = 'SetBodyColumn(600);PermSidebarObject.HidePermSidebar();';
	
	PageSettings["workspace"] = TempPageSettings;
	
	</SCRIPT>

<SCRIPT type="text/javascript">


var WorkspaceObject = new WorkspaceClass();

function WorkspaceClass(){
	this.HideReports = function(){
		$('#WorkspaceReports').slideUp("slow", function(){
			$('#WorkspaceReportExpandLink').show();
			
			$('#WorkspaceReportHeaderDiv').css('cursor', 'pointer');
			$('#WorkspaceReportHeaderDiv').click(function(){WorkspaceObject.ShowReports()});
		});
		$('#WorkspaceReportMinimizeLink').hide();
		
		$.post("/appinclude/action/dashboard/save_report_view.php", {HideWorkspaceReports:"1"}, function(Data){
			
		});
	}
	
	this.ShowReports = function(){
		$('#WorkspaceReportHeaderDiv').css('cursor', 'default');
		$('#WorkspaceReportHeaderDiv').unbind();
		$('#WorkspaceReportHeaderDiv').attr('onclick', "");
		
		$('#WorkspaceReports').slideDown("fast", function(){
			$('#WorkspaceReportMinimizeLink').show();
		});
		$('#WorkspaceReportExpandLink').hide();
		
		$.post("/appinclude/action/dashboard/save_report_view.php", {HideWorkspaceReports:"0"}, function(Data){
			
		});
	}
}

</SCRIPT>

<DIV id="DashboardContactsResult"></DIV></DIV>
<DIV id="AJAXPAGE_workspace_settings" class="AJAXPageTemplate"></DIV>
<DIV id="AJAXPAGE_reports__active" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'View Report - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = 'PermSidebarObject.HidePermSidebar();LogAnalyticsModule("Reporting");';
	
	PageSettings["reports__active"] = TempPageSettings;
	
	</SCRIPT>

<STYLE>

.ReportFilterOptionsDiv{
	background-color:#f5f5f5;
	border:1px solid #cccccc;
	border-bottom:0;
	padding:5px 15px;
	
	-webkit-border-top-left-radius: 5px;
	-webkit-border-top-right-radius: 5px;
	-moz-border-radius-topleft: 5px;
	-moz-border-radius-topright: 5px;
	border-top-left-radius: 5px;
	border-top-right-radius: 5px;
}

.ReportNotePriority{
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	font-size:10px;
	background-color:#000000;
	padding:4px 3px;
	width:90px;
	text-align:center;
	margin-top:5px;
}


</STYLE>

<SCRIPT type="text/javascript">

var ActiveReportObject = new ActiveReportClass();	
function ActiveReportClass(){
	this.Page = 1;
	this.PageSize = '';
	this.FilterOwner = '';
	this.SortField = '';
	this.SortDirection = '';
	this.StatusFilter = '';
	this.PipelineId = '';
	this.SaveStatusFilter = 0;
	this.SaveSort = 0;
	this.SaveFilterOwner = 0;
	
	this.Init = function(NewData){
		ResizeEvent = "ActiveReportObject.AdjustWidth()";
		
		//If NewData is defined (which it always should be), use it to set all the instance variables
		if(NewData != null){
			eval("var Data = NewData");
			this.Page = Data['Page'];
			this.PageSize = '';
			this.FilterOwner = Data['FilterOwner'];
			this.SortField = Data['SortField'];
			this.SortDirection = Data['SortDirection'];
			this.PipelineId = Data['PipelineId'];
			this.StatusFilter = Data['StatusFilter'];
			this.SaveStatusFilter = 0;
			this.SaveSort = 0;
			this.SaveFilterOwner = 0;
		}
		
		//If we're on anything other than the first page and there are no results, reload using the first page
		if(this.Page > 1 && $('[id^="ReportEditLink_"]').length == 0){
			this.Page = 1;
			this.BuildNewURL();
		}
		
		this.AdjustWidth();
		PermSidebarObject.StoreReturnURL();
	}
	
	this.AdjustWidth = function(){
		//$('.ReportContentColumn').css('max-width', "400px");
		$('.ReportContentColumn').css('max-width', Math.floor(parseInt($('#BodyMain').width())/2.5) +"px");
	}
	
	this.GoToPage = function(PageNum){
		this.Page = PageNum;
		this.BuildNewURL();
	}
	
	this.ChangePageSize = function(Element){
		this.PageSize = $(Element).val();
		this.BuildNewURL();
	}
	
	this.BuildNewURL = function(DontScroll){
		//We include the date to simulate a random number. This makes it so the URL will change so
		//the page will refresh even if the parameters haven't changed
		var d = new Date();
		HREF = "/app/reports/Active?PipelineId="+this.PipelineId+"&t="+d.getTime();
		if(this.Page != 1)
			HREF += "&Page="+this.Page;
		if(this.PageSize != '')
			HREF += "&PageSize="+this.PageSize;
		if(this.StatusFilter != '')
			HREF += "&StatusFilter="+this.StatusFilter;
		if(this.SaveStatusFilter == 1)
			HREF += "&SaveStatusFilter=true";
		if(this.SaveSort == 1)
			HREF += "&SaveSort=true";
		if(this.SaveOwnerFilter == 1)
			HREF += "&SaveFilterOwner=true";
		if(this.FilterOwner != '')
			HREF += "&FilterOwner="+this.FilterOwner;
		if(this.SaveSort == 1)
			HREF += "&SaveSort=true";
		if(this.SortField != '')
			HREF += "&SortField="+this.SortField;
		if(this.SortDirection != '')
			HREF += "&SortDirection="+this.SortDirection;
		
		//Navigate to the new URL
		if(HREF == window.location.hash.replace("#", "")){
			//reload the current page
			if(DontScroll!=true)
				DontScroll=false;
			LoadPage(HREF, DontScroll);
		}
		else{
			LoadPage(HREF, DontScroll);
			//jQuery.history.load(HREF);
		}
	}
	
	this.FilterStatusDialog = function(){
		DialogId = Dialog("<div id='ActiveReportDialogDiv'></div>", 500, "ActiveReportObject.CloseFilterStatusDialog();");
		$('#ActiveReportStatusFilterDialogDiv').appendTo("#ActiveReportDialogDiv");
		RepositionDialog(DialogId, 500);
	}
	
	this.CloseFilterStatusDialog = function(){
		$('#ActiveReportStatusFilterDialogDiv').appendTo("#ActiveReportStatusFilterDialogWrapper");
		CloseDialog('#ActiveReportDialogDiv');
	}
	
	this.SetStatusFilter = function(){
		this.StatusFilter = $("input[name='FilterStatusReport']:checked").val();
		if($('#FilterStatusReportDefault:checked').val() !== undefined)
			this.SaveStatusFilter = 1;
		this.Page = 1;
		this.BuildNewURL();
		this.CloseFilterStatusDialog();
	}
	
	this.FilterOwnerDialog = function(){
		DialogId = Dialog("<div id='ActiveReportDialogDiv'></div>", 500, "ActiveReportObject.CloseFilterOwnerDialog();");
		$('#ActiveReportOwnerFilterDialogDiv').appendTo("#ActiveReportDialogDiv");
		RepositionDialog(DialogId, 500);
	}
	
	this.CloseFilterOwnerDialog = function(){
		$('#ActiveReportOwnerFilterDialogDiv').appendTo("#ActiveReportOwnerFilterDialogWrapper");
		CloseDialog('#ActiveReportDialogDiv');
	}
	
	this.SetOwnerFilter = function(){
		this.FilterOwner = $("input[name='FilterOwnerReport']:checked").val();
		this.Page = 1;
		if($('#FilterOwnerReportDefault:checked').val() !== undefined)
			this.SaveOwnerFilter = 1;
		this.BuildNewURL();
		this.CloseFilterOwnerDialog();
	}
	
	this.SortDialog = function(){
		DialogId = Dialog("<div id='ActiveReportDialogDiv'></div>", 500, "ActiveReportObject.CloseSortDialog();");
		$('#ActiveReportSortDialogDiv').appendTo("#ActiveReportDialogDiv");
		RepositionDialog(DialogId, 500);
	}
	
	this.CloseSortDialog = function(){
		$('#ActiveReportSortDialogDiv').appendTo("#ActiveReportSortDialogWrapper");
		CloseDialog('#ActiveReportDialogDiv');
	}
	
	this.SetSort = function(){
		this.SortField = $("input[name='SortFieldReport']:checked").val();
		this.SortDirection = $("input[name='SortDirectionReport']:checked").val();
		this.Page = 1;
		if($('#SortReportDefault:checked').val() !== undefined)
			this.SaveSort = 1;
		this.BuildNewURL();
		this.CloseFilterStatusDialog();
	}
	
	this.ShowEditOptions = function(OpportunityId){
		//$('#ReportEditLink_'+OpportunityId).show();
	}
	
	this.HideEditOptions = function(OpportunityId){
		//$('#ReportEditLink_'+OpportunityId).hide();
	}	
}
	
</SCRIPT>

<DIV id="FrameworkActiveReport"></DIV></DIV>
<DIV id="AJAXPAGE_edit_contact" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Edit Contact - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = 'EditContactObject.Reset()';
	
	PageSettings["edit_contact"] = TempPageSettings;
	
	</SCRIPT>

<SCRIPT type="text/javascript">
var EditContactObject = new EditContactClass();	

function EditContactClass(){
	this.ContactId = "";
	this.EmailCount = 1;
	this.PhoneCount = 1;
	this.AddressCount = 1;
	this.WebsiteCount = 1;
	
	this.Reset = function(){
		$('#FrameworkEditContactDiv').html('');
	}
	
	this.Init = function(){		
		$('#FrameworkEditContactDiv').find('.DeleteField').bind('mouseover', function(){
			$(this).attr('src', '/i/app/delete_field_highlighted.png');
		});
		$('#FrameworkEditContactDiv').find('.DeleteField').bind('mouseout', function(){
			$(this).attr('src', '/i/app/delete_field.png');
		});
		
		AddTextAreaDefault("#EditBackgroundInfo", "Use this space to enter any information that doesn't fit in one of the fields above (e.g., how you met, name of spouse, etc)", '#bbbbbb');
		
		AddTextAreaDefault("[id^=EditAddress][id*=Street]", "Street", "#bbbbbb");
		AddTextAreaDefault("[id^=EditAddress][id*=City]", "City", "#bbbbbb");
		AddTextAreaDefault("[id^=EditAddress][id*=State]", "State", "#bbbbbb");
		AddTextAreaDefault("[id^=EditAddress][id*=Zip]", "Zip", "#bbbbbb");
		AddTextAreaDefault("[id^=EditAddress][id*=Country]", "Country", "#bbbbbb");
		
		SetUpAutoComplete('#EditCompanyName');
		
	}
	
	this.AddField = function(FieldType, ThisCount){
		$('#'+FieldType+'Fields').find('.AddContactExtraField').parent().before('<div class="AddContactExtraFields">'+$('#EditMultiForm_'+FieldType).html().replace(/xxx/g, ThisCount)+'</div>');
		
		if(FieldType == 'EditAddress'){
			AddTextAreaDefault("[id^=EditAddress][id*=Street]", "Street", "#bbbbbb");
			AddTextAreaDefault("[id^=EditAddress][id*=City]", "City", "#bbbbbb");
			AddTextAreaDefault("[id^=EditAddress][id*=State]", "State", "#bbbbbb");
			AddTextAreaDefault("[id^=EditAddress][id*=Zip]", "Zip", "#bbbbbb");
			AddTextAreaDefault("[id^=EditAddress][id*=Country]", "Country", "#bbbbbb");
		}
		
		$('.DeleteField').unbind('mouseover');
		$('.DeleteField').unbind('mouseout');
		
		$('.DeleteField').bind('mouseover', function(){
			$(this).attr('src', '/i/app/delete_field_highlighted.png');
		});
		$('.DeleteField').bind('mouseout', function(){
			$(this).attr('src', '/i/app/delete_field.png');
		});
		
		//Focus on the first form field for the new element
		if($('#'+FieldType+'_'+ThisCount).find("textarea").length > 0){
			//This is the address field
			$('#'+FieldType+'_'+ThisCount).find("textarea").focus();
		}
		else{
			$('#'+FieldType+'_'+ThisCount).find("input:first").focus();
		}
		
		
		eval("this."+FieldType.replace('Edit', '')+"Count++");
			
		//$('#FakeDiv').show();
	
	}

	this.RemoveField = function(FieldType, ThisCount){
		$('#'+FieldType+'_'+ThisCount).remove();
	}
	
	this.ShowCollapsedField = function(FieldId){
		$('#EditShowFieldLink_'+FieldId).hide();
		$('#EditExpandedField_'+FieldId).show();
		
		if($('#EditExpandedField_'+FieldId).find("textarea").length > 0){
			//This is the address field
			$('#EditExpandedField_'+FieldId).find("textarea").focus();
		}
		else{
			$('#EditExpandedField_'+FieldId).find("input:first").focus();
		}
	}
	
	this.Save = function(){
		GrayOutArea("#EditContactStylingDiv", true);
		$.post("/appinclude/action/view_contact/edit_contact.php", $('#EditContactForm').serialize(), function(Data){
			EndGrayOutArea();
			
			//CloseDialogs();
			//Dialog(Data);
			InsertMarkupFromAJAX(Data);
		});
	}
	
}
</SCRIPT>

<DIV id="FrameworkEditContactDiv"></DIV></DIV>
<DIV id="AJAXPAGE_browse" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Browse Contacts - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = 'BrowseContactsObject.Reset();LogAnalyticsModule("CRM");';
	
	PageSettings["browse"] = TempPageSettings;
	
	</SCRIPT>

<STYLE>
.SearchDiv{
	margin-bottom:10px;
}

.SearchOptionsDiv{
	border-bottom:1px solid #cccccc;
	
	background: #f5f5f5;
	background: -moz-linear-gradient(top, #eeeeee 0%, #d5d5d5 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#eeeeee), color-stop(100%,#d5d5d5));
	background: -webkit-linear-gradient(top, #eeeeee 0%,#d5d5d5 100%);
	background: -o-linear-gradient(top, #eeeeee 0%,#d5d5d5 100%);
	background: -ms-linear-gradient(top, #eeeeee 0%,#d5d5d5 100%);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#eeeeee', endColorstr='#d5d5d5',GradientType=0 );
	background: linear-gradient(top, #eeeeee 0%,#d5d5d5 100%);
}

.SearchOptionsDiv td{
	padding:5px 10px;
}

.SearchOptionsSelectable{
	border-right:1px solid #ccc;
	cursor:pointer;
	white-space:nowrap;
}

.SearchOptionsSelectable:hover{
	background: #dddddd;
	background: -moz-linear-gradient(top, #dddddd 0%, #c5c5c5 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#dddddd), color-stop(100%,#c5c5c5));
	background: -webkit-linear-gradient(top, #dddddd 0%,#c5c5c5 100%);
	background: -o-linear-gradient(top, #dddddd 0%,#c5c5c5 100%);
	background: -ms-linear-gradient(top, #dddddd 0%,#c5c5c5 100%);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#dddddd', endColorstr='#c5c5c5',GradientType=0 );
	background: linear-gradient(top, #dddddd 0%,#c5c5c5 100%);
}

.SearchOptionType{
	font-size:10px;
	color:#999;
}

.SearchOptionVal{
	overflow:hidden;
	text-overflow: ellipsis;
	text-decoration:none;
	font-size:12px;
	color:#444;
}

.SearchFooterDiv{
	border-bottom:1px solid #cccccc;
	border-top:0;
	padding:10px 15px;
	background: #e5e5e5;
	background: -moz-linear-gradient(top, #e5e5e5 0%, #dddddd 100%);
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#e5e5e5), color-stop(100%,#dddddd));
	background: -webkit-linear-gradient(top, #e5e5e5 0%,#dddddd 100%);
	background: -o-linear-gradient(top, #e5e5e5 0%,#dddddd 100%);
	background: -ms-linear-gradient(top, #e5e5e5 0%,#dddddd 100%);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e5e5e5', endColorstr='#dddddd',GradientType=0 );
	background: linear-gradient(top, #e5e5e5 0%,#dddddd 100%);
}

.OptionsBar{
	margin-top:10px;
	border-bottom:1px solid #999999;
	height:30px;
	vertical-align:bottom;
	z-index:5;
	position:relative;
}

#SortByDiv{
	background-image:url(/i/app/fade_divider.png);
	background-repeat:no-repeat;
	background-position:bottom left;
	width:160px;
	height:30px;
	overflow:hidden;
	padding:0px 5px;
	position:relative;
	cursor:pointer;
	z-index:5;
	float:right;
}

#FilterDiv{
	background-image:url(/i/app/fade_divider.png);
	background-repeat:no-repeat;
	background-position:bottom left;
	width:210px;
	height:30px;
	overflow:hidden;
	padding:0px 5px;
	position:relative;
	cursor:pointer;
	z-index:5;
	float:right;
}

.DropdownBar{
	position:relative;
	z-index:5px;
	height:0px;
}

.SortOption{
	padding: 4px 4px;
	border-top:1px solid #cccccc;
	cursor:pointer;
}

.SortOption:hover{
	background-color:#cccccc;
}

.ContactRow{
	height:55px;
	position:relative;
	z-index:1;
	border-bottom:1px solid #cccccc;
	padding-left:17px;
}

.HighlightedContactRow, .HighlightedRow{	
	background-color:#f5f5f5;
}

.ContactCheckbox{
	position:relative;
	top:2px;
}

.ContactNameDiv{
	position:absolute;
	left:50px;
	top:8px;
	line-height:20px;
	width:360px;
	overflow:hidden;
	padding-left:20px;
}

.ContactName{
	height:20px;
	overflow:hidden;
	text-overflow: ellipsis;
	white-space:nowrap;
}

.ContactName a{
	font-size:16px;
	font-weight:bold;
}

.CompanyLine{
	color:#999999;
	margin-top:3px;
	line-height:16px;
	text-overflow: ellipsis;
	white-space:nowrap;
	overflow:hidden;
	width:380px;
}

.CompanyLine a{
	color:#999999;
	text-decoration:none;
}

.CompanyLine a:hover{
	text-decoration:underline;
	color:#666666;
}

.GrayLink{
	color:#999999;
	text-decoration:none;
}
.GrayLink:hover{
	color:#999999;
	text-decoration:underline;
}

.BasicContactInfo{
	position:absolute;
	left:450px;
	top:3px;
	line-height:24px;
	width:300px;
	overflow:hidden;
	
}

.BasicContactInfo div{
	text-overflow:ellipsis;
	white-space:nowrap;
}

.ContactInfoLeft{
	
	overflow:hidden;
	float:left;
	margin-right:5px;
	text-overflow:ellipsis;
	white-space:nowrap;
}

.ContactInfoLeft a{
	text-decoration:none;
}
.ContactInfoLeft a:hover{
	text-decoration:underline;
}

.ContactInfoRight{
	width:60px;
	overflow:hidden;
	float:left;
	font-size:10px;
	color:#999999;
}

.AllEmployeesDiv{
	width:700px;
	max-height:30px;
	overflow:hidden;
	font-size:10px;
	line-height:14px;
	margin-top:3px;
	color:#999999;
	
}

.EmployeeDiv{
	float:left;
	margin-right:6px;
}

.EmployeeNameLink{
	text-decoration:none;
	color:#666666;
}

.EmployeeNameLink:hover{
	text-decoration:underline;
}

#SearchResults{
	position:relative;
	min-height:400px;
	width:768px;
}

#FilterOptionsDropdown{
	width:230px;
}

.BrowseFilterName{
	font-size:10px;
	color:#999999;
}

.BrowseFilterOption{
	font-size:11px;
	color:#999999;
}

#BrowseCheckedOptionsDiv{
	width:100%;
	background-color:red;
	position:fixed;
	bottom:0px;
	z-index:100;
	overflow:hidden;
	box-shadow: 0px 0px 15px #000;
}

#BrowseCheckedOptionLinks a{
	color:#fff;
	font-weight:bold;
}

</STYLE>

<SCRIPT type="text/javascript">

$(function(){
	//Overload the behavior of the sidebar search
	$('#SidebarSearchForm').submit(function(){
		//HREF = "/app/Browse?Search="+escape($('#SidebarSearch').val())+"&SortField=Relevance&SortDirection=DESC";
		HREF = "/app/Browse?Search="+encodeURIComponent($('#SidebarSearch').val())+"&SortField=Relevance&SortDirection=DESC";
		
		if(HREF == window.location.hash.replace("#", "")){
			//reload the current page
			LoadPage(HREF);
		}
		else{
			jQuery.history.load(HREF);
		}
		
		$('#SidebarSearch').val('');
		$('#SidebarSearch').blur();
		return false;
	});
	
	$('#BigSearchBox').bind('keydown', 'return', function(){
		BrowseContactsObject.RunSearch();
	});
	
});


var SearchTextHelp = "Enter a contact's name, email, phone number, etc.";
var BrowseContactsObject = new BrowseContactsClass();	

function BrowseContactsClass(){
	this.SearchTerms = '';
	this.Page = 1;
	this.PageSize = '';
	this.FilterType = '';
	this.FilterOwner = '';
	this.SortField = '';
	this.SortDirection = '';
	this.SaveSort = 0;
	this.SaveFilterType = 0;
	this.SaveFilterOwner = 0;
	this.AllContactsSelected=false;
	this.GroupId = 0;
	
	//This is called when the page loads, before the AJAX has loaded
	this.Reset = function(){
		this.AllContactsSelected=false;
		ResizeEvent = "BrowseContactsObject.AdjustWidth()";
		PermSidebarObject.HidePermSidebar()
	}
	
	this.AdjustWidth = function(){
		$('#BigSearchBox').css('width', $('#BodyMain').width() - 305+'px');
		$('#BrowseCheckedOptionsDiv').width($('.MainContent').width());
	}
	
	//This is called after the AJAX has loaded
	this.Init = function(NewData){
		//If NewData is defined (which it always should be), use it to set all the instance variables
		if(NewData != null){
			eval("var Data = NewData");
			this.SearchTerms = Data['SearchTerms'];
			this.Page = Data['Page'];
			this.PageSize = '';
			this.FilterType = Data['FilterType'];
			this.FilterOwner = Data['FilterOwner'];
			this.SortField = Data['SortField'];
			this.SortDirection = Data['SortDirection'];
			this.GroupId = Data['GroupId'];
			
			this.SaveSort = 0;
			this.SaveFilterType = 0;
			this.SaveFilterOwner = 0;
			
			$('#BigSearchBox').val(this.SearchTerms);
		}
	
		AddTextAreaDefault("#BigSearchBox", SearchTextHelp);
		
		this.UpdateSortDefaultDisplay();
		
		$('[id^="SortFieldBrowseRadioOption_"]').unbind('click');
		$('[id^="SortFieldBrowseRadioOption_"]').bind('click', function(){
			BrowseContactsObject.UpdateSortDefaultDisplay();
		});
		this.AdjustWidth();
		
		PermSidebarObject.StoreReturnURL();
	}
	
	//This reloads the page with new URL parameters (it's not necessarily just for search)
	this.RunSearch = function(){
		this.SearchTerms = $('#BigSearchBox').val();
		this.SortField = "Relevance";
		this.SortDirection = "DESC";
		this.Page = 1;
		this.BuildNewURL();
	}
	
	this.GoToPage = function(PageNum){
		this.Page = PageNum;
		this.BuildNewURL();
	}
	
	this.ChangePageSize = function(Element){
		this.Page = 1;
		this.PageSize = $(Element).val();
		this.BuildNewURL();
	}
	
	this.BuildNewURL = function(){
		//We include the date to simulate a random number. This makes it so the URL will change so
		//the page will refresh even if the parameters haven't changed
		var d = new Date();
		
		HREF = "/app/Browse?t="+d.getTime();
		//if(this.SearchTerms)
		//	HREF += "&Search="+escape(this.SearchTerms);
		if(this.SearchTerms)
			HREF += "&Search="+encodeURIComponent(this.SearchTerms);
		if(this.Page != 1)
			HREF += "&Page="+this.Page;
		if(this.PageSize != '')
			HREF += "&PageSize="+this.PageSize;
		if(this.SortField != '')
			HREF += "&SortField="+this.SortField;
		if(this.SortDirection != '')
			HREF += "&SortDirection="+this.SortDirection;
		if(this.SaveSort == 1)
			HREF += "&SaveSort=true";
		if(this.FilterType != '')
			HREF += "&FilterType="+this.FilterType;
		if(this.SaveFilterType == 1)
			HREF += "&SaveFilterType=true";
		if(this.FilterOwner != '')
			HREF += "&FilterOwner="+this.FilterOwner;
		if(this.SaveFilterOwner == 1)
			HREF += "&SaveFilterOwner=true";
		if(this.GroupId > 0)
			HREF += "&GroupId="+this.GroupId;

		//Navigate to the new URL
		if(HREF == window.location.hash.replace("#", "")){
			//reload the current page
			LoadPage(HREF);
		}
		else{
			jQuery.history.load(HREF);
		}
	}
	
	this.GroupDialog = function(){
		DialogFromSource("GroupSearchFilter");
	}
	
	this.SetGroup = function(GroupId){
		this.GroupId = GroupId;
		this.Page = 1;
		this.BuildNewURL();
		CloseDialogFromSource("GroupSearchFilter");
	}
	
	this.SortDialog = function(){
		DialogId = Dialog("<div id='BrowseDialogDiv'></div>", 500, "BrowseContactsObject.CloseSortDialog();");
		$('#BrowseSortDialogDiv').appendTo("#BrowseDialogDiv");
		RepositionDialog(DialogId, 500);
	}
	
	this.CloseSortDialog = function(){
		$('#BrowseSortDialogDiv').appendTo("#BrowseSortDialogWrapper");
		CloseDialog('#BrowseDialogDiv');
	}
	
	this.SetSort = function(){
		this.SortField = $("input[name='SortFieldBrowse']:checked").val();
		this.SortDirection = $("input[name='SortDirectionBrowse']:checked").val();
		this.Page = 1;
		if($('#SortBrowseDefault:checked').val() !== undefined)
			this.SaveSort = 1;
		this.BuildNewURL();
		this.CloseSortDialog();
	}
	
	//if the "Search Relevance" sort option is selected, don't allow it to be the default
	this.UpdateSortDefaultDisplay = function(){
		if($("input[name='SortFieldBrowse']:checked").val() == 'Relevance'){
			$('#SortBrowseDefaultDiv').hide();
			$('#SortBrowseDefault').removeAttr('checked');
		}
		else{
			$('#SortBrowseDefaultDiv').show();
		}
	}
	
	this.FilterTypeDialog = function(){
		DialogId = Dialog("<div id='BrowseDialogDiv'></div>", 500, "BrowseContactsObject.CloseFilterTypeDialog();");
		$('#BrowseFilterTypeDialogDiv').appendTo("#BrowseDialogDiv");
		RepositionDialog(DialogId, 500);
	}
	
	this.CloseFilterTypeDialog = function(){
		$('#BrowseFilterTypeDialogDiv').appendTo("#BrowseFilterTypeDialogWrapper");
		CloseDialog('#BrowseDialogDiv');
	}
	
	this.SetFilterType = function(){
		this.FilterType = $("input[name='FilterTypeBrowse']:checked").val();
		this.Page = 1;
		if($('#FilterTypeBrowseDefault:checked').val() !== undefined)
			this.SaveFilterType = 1;
		this.BuildNewURL();
		this.CloseSortDialog();
	}
	
	this.FilterOwnerDialog = function(){
		DialogId = Dialog("<div id='BrowseDialogDiv'></div>", 500, "BrowseContactsObject.CloseFilterOwnerDialog();");
		$('#BrowseFilterOwnerDialogDiv').appendTo("#BrowseDialogDiv");
		RepositionDialog(DialogId, 500);
	}
	
	this.CloseFilterOwnerDialog = function(){
		$('#BrowseFilterOwnerDialogDiv').appendTo("#BrowseFilterOwnerDialogWrapper");
		CloseDialog('#BrowseDialogDiv');
	}
	
	this.SetFilterOwner = function(){
		this.FilterOwner = $("input[name='FilterOwnerBrowse']:checked").val();
		this.Page = 1;
		if($('#FilterOwnerBrowseDefault:checked').val() !== undefined)
			this.SaveFilterOwner = 1;
		this.BuildNewURL();
		this.CloseSortDialog();
	}
	
	this.SelectAll = function(){
		if($('.ContactCheckbox:not(:checked)').length == 0){
			$('.ContactCheckbox, #SearchContactsSelectAll').removeAttr('checked');
			this.ProcessCheckContact();
		}
		else{
			$('.ContactCheckbox').attr('checked', 'checked');
			this.ProcessCheckContact();
		}
	}
	
	this.SelectNone = function(){
		$('.ContactCheckbox, #SearchContactsSelectAll').removeAttr('checked');
		this.ProcessCheckContact();
	}
	
	this.ReallySelectAll = function(){
		$('#BrowseCheckedSelectMoreDiv').hide();
		$('#BrowseCheckedAllSelectedDiv').fadeIn('slow');
		this.AllContactsSelected = true;
	}
	
	this.ShowActions = function(){
		$('#ActionsDropdown').slideDown('fast');
	}
	
	this.ProcessCheckContact = function(){
		NumChecked = parseInt($('.ContactCheckbox:checked').length);
		NumNotChecked = parseInt($('.ContactCheckbox').length) - NumChecked;
		TotalRows = parseInt($('#NumSearchResults').val());
		
		//Handle all contacts checked
		if(NumNotChecked == 0){
			//Check if there are more pages to this report
			if(TotalRows > NumChecked){
				
				$('#BrowseCheckedSelectMoreDiv').slideDown('fast');
				$('.NumContactsSelectedSpan').html(NumChecked);
				$('.NumContactsTotalSpan').html(TotalRows);
			}
		}
		else{
			this.AllContactsSelected = false;
			$('#BrowseCheckedAllSelectedDiv').slideUp('fast');
			$('#BrowseCheckedSelectMoreDiv').slideUp('fast');
			$('#SearchContactsSelectAll').removeAttr('checked');
		}
		
		//Show the Actions option
		if(NumChecked > 0){
			$('#BrowseCheckedOptionsDiv').slideDown('fast');
		}
		else{
			$('#BrowseCheckedOptionsDiv').slideUp('fast');
		}
	}
	
	this.DeleteContacts = function(){
		if($('.ContactCheckbox:checked').length == 0){
			return;
		}
		else{
			NumChecked = parseInt($('.ContactCheckbox:checked').length);
			Dialog("<div style='padding:20px;'><div style='font-size:14px; color:#999999; font-weight:bold;' align='center'>Are you sure that you want to delete "+($('.ContactCheckbox:checked').length == 1 ? "this contact?" : "these contacts?")+"</div><br /><br />"+
				"<div align='center'><strong><a href='javascript://' onclick='BrowseContactsObject.ConfirmDelete();CloseDialog($(this).parent());'>Yes, delete</a></strong><span style='padding:20px;'></span><a href='javascript://' onclick='CloseDialog($(this).parent())'>Cancel</a></div></div>");
			
		}
	}
	
	this.ConfirmDelete = function(){
		GrayOutArea('#FrameworkBrowseContacts', false);
		$('#FrameworkBrowseContacts').append("<div id='CheckedContactsLoadingDiv' style='z-index:999999; border:3px solid #3d6aa6; padding:30px; color:#3d6aa6; font-weight:bold; font-size:24px; position:fixed; top:200px;background-color:white;' align='center'>Deleting contacts, this may take a few moments...<br /><br /><img src='style/default/images/main/loading.gif' /><br /></div>");
		$('#CheckedContactsLoadingDiv').css('left', ($(window).width()- 300  - $('#CheckedContactsLoadingDiv').width()) /2);
		$('#BrowseCheckedOptionsDiv').slideUp('fast');
	
		var SearchTerms = $('#BigSearchBox').val();
		if(SearchTerms == SearchTextHelp)
			SearchTerms = '';
		var CheckedContacts = '';
		$('.ContactCheckbox:checked').each(function(){
			CheckedContacts += $(this).attr("ContactId") + ",";
		});
		
		$.post('/appinclude/action/browse/delete_contacts.php', {Search:SearchTerms, Contacts:CheckedContacts, AllContacts:this.AllContactsSelected, FilterType:this.FilterType, FilterOwner:this.FilterOwner, GroupId:this.GroupId}, function(data){
			InsertMarkupFromAJAX(data);
			CloseDialogs();
		});
	}
	
	this.ShowGroupDialog = function(){
		AddGroupObject = this;
		GroupObject.AddContactToGroup("Add "+($('.ContactCheckbox:checked').length == 1 ? "this contact" : "these contacts")+" to a group");
	}
	
	this.AddContactToGroup = function(ThisGroupId){
		GrayOutArea('#AddContactToGroup', true);
		
		var SearchTerms = $('#BigSearchBox').val();
		if(SearchTerms == SearchTextHelp)
			SearchTerms = '';
		var CheckedContacts = '';
		$('.ContactCheckbox:checked').each(function(){
			CheckedContacts += $(this).attr("ContactId") + ",";
		});
		
		$.post('/appinclude/action/browse/add_to_group.php', {NewGroupId:ThisGroupId, Search:SearchTerms, Contacts:CheckedContacts, AllContacts:this.AllContactsSelected, FilterType:this.FilterType, FilterOwner:this.FilterOwner, GroupId:this.GroupId},
		function(data){
			InsertMarkupFromAJAX(data);
			EndGrayOutArea();
			CloseDialog($('#AddContactToGroup').parent());
		});
	}
	
	this.CreateGroupAndAddContact = function(){
		if($('#AddContactToGroup #AddToGroupNewGroupName').val() == '' || $('#AddContactToGroup #AddToGroupNewGroupName').val() == "Enter group name"){
			$('#AddContactToGroup .GroupNameWarning').fadeIn("fast");
			return;
		}
		
		var SearchTerms = $('#BigSearchBox').val();
		if(SearchTerms == SearchTextHelp)
			SearchTerms = '';
		var CheckedContacts = '';
		$('.ContactCheckbox:checked').each(function(){
			CheckedContacts += $(this).attr("ContactId") + ",";
		});
		
		$('#AddContactToGroup .GroupNameWarning').hide();
		$('#AddContactToGroup .GroupNameTaken').hide();
		
		GrayOutArea('#AddContactToGroup', true);
		
		$.post('/appinclude/action/browse/add_to_new_group.php', {GroupName:$('#AddContactToGroup #AddToGroupNewGroupName').val(), Search:SearchTerms, Contacts:CheckedContacts, AllContacts:this.AllContactsSelected, FilterType:this.FilterType, FilterOwner:this.FilterOwner, GroupId:this.GroupId},
		function(data){
			EndGrayOutArea();
			InsertMarkupFromAJAX(data);
			
		});
	}
	
	this.AssignOwnerDialog = function(){
		Dialog("<div id='AssignOwnerDialog'>"+$('#AssignOwnerBrowseDiv').html()+"</div>", 350);
		$('#AssignOwnerBrowserHeader').html("Who should "+($('.ContactCheckbox:checked').length == 1 ? "this contact" : "these  contacts")+"<br />be assigned to?");
		
	}
	
	this.AssignOwner = function(ThisUserId){
		GrayOutArea('#AssignOwnerDialog', true);
		
		
		var SearchTerms = $('#BigSearchBox').val();
		if(SearchTerms == SearchTextHelp)
			SearchTerms = '';
		var CheckedContacts = '';
		$('.ContactCheckbox:checked').each(function(){
			CheckedContacts += $(this).attr("ContactId") + ",";
		});
		
		$.post('/appinclude/action/browse/assign_user.php', {NewUserId:ThisUserId, Search:SearchTerms, Contacts:CheckedContacts, AllContacts:this.AllContactsSelected, FilterType:this.FilterType, FilterOwner:this.FilterOwner, GroupId:this.GroupId}, function(Data){
			InsertMarkupFromAJAX(Data);
			CloseDialog('#AssignOwnerDialog');
			BrowseContactsObject.SelectNone();
			SystemMessage("The contacts have been assigned to "+$('.AssignOwner_'+ThisUserId).html());
		});
	}
	
	this.ExportToExcel = function(){		
		Dialog("<div class='DialogHeader'>Exporting Contacts...</div><div style='padding:20px; font-size:14px; font-weight:bold;' id='ExportStatusDiv'><div align='center' style='padding:40px;'><img src='style/default/images/main/loading.gif' /></div></div>");
		
		$.post("/ajax/account/export/start_export.php", {Search:this.SearchTerms, FilterType:this.FilterType, FilterOwner:this.FilterOwner, GroupId:this.GroupId}, function(Data){
			Data = $.parseJSON(Data)
			$('#ExportStatusDiv').html(Data['Description']);
			BrowseContactsObject.CheckExport(1, Data['ExportId']);
		});
		//window.location = '/downloads/export.php?Search='+urlencode(this.SearchTerms)+'&FilterType='+this.FilterType+'&FilterOwner='+this.FilterOwner+"&GroupId="+this.GroupId;
	}

	this.CheckExport = function(Attempt, ThisExportId){
		$.post("/ajax/account/export/check_export.php", {ExportId:ThisExportId}, function(Data){
			if(Data == "TRUE"){
				//The export is finished!
				CloseDialogs();
				window.location = "/ajax/account/export/download_file_proxy.php?ExportId="+ThisExportId;
			}
			else{
				if(Attempt < 10){
					//The first few tries happen very frequently
					setTimeout("BrowseContactsObject.CheckExport("+(Attempt+1)+", "+ThisExportId+")", 1000);
				}
				else{
					//Then things slow down so we're not hitting the server too much
					setTimeout("BrowseContactsObject.CheckExport("+(Attempt+1)+", "+ThisExportId+")", 10000);
				}
			}
		});
	}
}

var RemoveContactsFromGroupObject = new RemoveContactsFromGroupClass();	

function RemoveContactsFromGroupClass(){
	this.ShowGroupDialog = function(){
		AddGroupObject = this;
		GroupObject.AddContactToGroup("Remove "+($('.ContactCheckbox:checked').length == 1 ? "this contact" : "these contacts")+" from a group");
		$('.QuickAddGroupName').hide();
	}
	
	this.AddContactToGroup = function(ThisGroupId){
		GrayOutArea('#AddContactToGroup', true);
		
		var SearchTerms = $('#BigSearchBox').val();
		if(SearchTerms == SearchTextHelp)
			SearchTerms = '';
		var CheckedContacts = '';
		$('.ContactCheckbox:checked').each(function(){
			CheckedContacts += $(this).attr("ContactId") + ",";
		});
		
		$.post('/appinclude/action/browse/remove_from_group.php', {GroupId:ThisGroupId, FilterGroupId:BrowseContactsObject.GroupId, Search:SearchTerms, Contacts:CheckedContacts, AllContacts:BrowseContactsObject.AllContactsSelected, FilterType:BrowseContactsObject.FilterType, FilterOwner:BrowseContactsObject.FilterOwner},
		function(data){
			InsertMarkupFromAJAX(data);
			EndGrayOutArea();
			CloseDialog($('#AddContactToGroup').parent());
		});
	}
}

</SCRIPT>

<DIV style="padding: 30px;" class="PageHeader"><INPUT style="padding: 4px; width: 500px; height: 26px; font-size: 16px; font-weight: bold; margin-right: 10px;" 
id="BigSearchBox" class="BoldFormField" type="text"><A style="padding-right: 70px; padding-left: 70px;" 
id="MainSearchButton" class="GreenButton" onclick="BrowseContactsObject.RunSearch();" 
href="javascript://">Search</A></DIV>
<DIV id="FrameworkBrowseContacts"></DIV></DIV>
<DIV id="AJAXPAGE_groups" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Manage your Groups - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = 'PermSidebarObject.HidePermSidebar();';
	
	PageSettings["groups"] = TempPageSettings;
	
	</SCRIPT>

<STYLE>

.OptionsHeaderDiv{
	background-color:#f5f5f5;
	border:1px solid #cccccc;
	padding:5px 15px;
	
	-webkit-border-top-left-radius: 5px;
	-webkit-border-top-right-radius: 5px;
	-moz-border-radius-topleft: 5px;
	-moz-border-radius-topright: 5px;
	border-top-left-radius: 5px;
	border-top-right-radius: 5px;
}

.OptionsTitle{
	font-size:26px;
	font-weight:bold;
	color:#999999;
}

.OptionsDescription{
	font-size:11px;
	color:#999999;
}

.OptionsRow{
	padding:5px;
	border-bottom:1px solid #cccccc;
}

</STYLE>

<SCRIPT type="text/javascript">

$(function(){
	$('#NewGroupGroupName').bind('keydown', 'return', function(){
		GroupObject.SaveGroup();
	});
});

var AddGroupObject = null; //This is the object that will be used to add a group to contact/contacts

var GroupObject = new GroupClass();	

function GroupClass(){
	this.EditGroupId;
	this.PublicRenameId;
	
	this.Init = function(){
		$('#PublicRenameGroupGroupName').bind('keydown', 'return', function(){
			GroupObject.SavePublicRename();
		})
		
		$('#EditGroupGroupName').bind('keydown', 'return', function(){
			GroupObject.SaveEdit();
		})
		
		SetBodyColumn(270);
	}
	
	this.NewGroupDialog = function(){
		$('#CreateGroupDuplicateNameWarning').hide();
		$('#CreateGroupEmptyNameWarning').hide();
		
		DialogId = Dialog("<div id='NewGroupDialog'></div>", 500, "GroupObject.CloseDialog()");
		$('#CreateGroupDiv').appendTo("#NewGroupDialog");
		RepositionDialog(DialogId, 500);
		$('#NewGroupGroupName').val('');
		$('#NewGroupGroupName').focus();
	}
	
	this.CloseDialog = function(){
		$('#CreateGroupDiv').appendTo("#CreateGroupWrapper");
		CloseDialog('#NewGroupDialog');
	}
	
	this.SaveGroup = function(){
		ThisGroupName = $('#NewGroupGroupName').val();
		
		if(ThisGroupName == ''){
			$('#CreateGroupEmptyNameWarning').fadeIn('fast');
			return;
		}
		else{
			$('#CreateGroupEmptyNameWarning').hide();
		}
		
		var Public = 0;
		if ($('#NewGroupIsPublic:checked').val() !== undefined)
			Public = 1;
		
		GrayOutArea('#CreateGroupDiv', true);
		$.post('/appinclude/action/groups/new_group.php', {GroupName:ThisGroupName, IsPublic:Public}, function(Data){
			EndGrayOutArea();
			InsertMarkupFromAJAX(Data);
		});
	}
	
	this.ShowError = function(){
		$('#CreateGroupDuplicateNameWarning').fadeIn('fast');
		return;
	}
	
	this.ConfirmForm = function(NewGroupId){
		if(CurrentPage.toLowerCase() == '/app/groups')
			jQuery.history.load("/app/Groups?NewGroup="+NewGroupId);
		this.CloseDialog();
	}
	
	this.DeleteDialog = function(GroupId){
		var GroupName = $('#ManageGroup_'+GroupId).html();
		
		Dialog("<div style='padding:20px;'><div id='DeleteGroupDialogWrapper'><div id='DeleteGroupDialog' style='color:#999999; font-size:18px; font-weight:bold; margin-bottom:10px;' align='center'>Are you sure you want to delete the group <em>"+GroupName+"</em>?</div><div style='font-size:12px; color:#999999; margin-bottom:20px;' align='center'>This will not delete the contacts in this group, it will only delete the group label.</div><div align='center'><a href='javascript://' onclick='GroupObject.ConfirmDelete("+GroupId+");' style='font-weight:bold;'>Yes, delete the group</a><span style='padding:20px;'></span><a href='javascript://' onclick='CloseDialog($(this).parent().parent());' style='color:#999999;'>Cancel</a></div></div></div>");
	}
	
	this.ConfirmDelete = function(ThisGroupId){
		var GroupName = $('#ManageGroup_'+ThisGroupId).html();
		GrayOutArea($('#DeleteGroupDialogWrapper').parent(), true);
		
		$.post('/appinclude/action/groups/delete_group.php', {GroupId:ThisGroupId}, function(data){
			EndGrayOutArea();
			CloseDialog('#DeleteGroupDialogWrapper');
			SystemMessage("The group <em>"+GroupName+"</em> has been deleted");
			InsertMarkupFromAJAX(data);
		});
	}
	
	this.EditDialog = function(GroupId){
		this.EditGroupId = GroupId
		
		$('#EditGroupDuplicateNameWarning').hide();
		$('#EditGroupEmptyNameWarning').hide();
		
		DialogId = Dialog("<div id='EditGroupDialog'></div>", 500, "GroupObject.CloseEditDialog()");
		$('#EditGroupDiv').appendTo("#EditGroupDialog");
		RepositionDialog(DialogId, 500);
		$('#EditGroupGroupName').val($('#ManageGroup_'+GroupId).html());
		$('#EditGroupGroupName').focus();
	}
	
	this.CloseEditDialog = function(){
		$('#EditGroupDiv').appendTo("#EditGroupWrapper");
		CloseDialog('#EditGroupDialog');
	}
	
	this.SaveEdit = function(){
		ThisGroupName = $('#EditGroupGroupName').val();
		
		if(ThisGroupName == ''){
			$('#EditGroupEmptyNameWarning').fadeIn('fast');
			return;
		}
		else{
			$('#EditGroupEmptyNameWarning').hide();
		}
		
		GrayOutArea('#EditGroupDiv', true);
		$.post('/appinclude/action/groups/edit.php', {GroupId:this.EditGroupId, GroupName:ThisGroupName}, function(Data){
			EndGrayOutArea();
			InsertMarkupFromAJAX(Data);
		});
	}
	
	this.MakePublic = function(ThisGroupId){
		GrayOutArea('#FrameworkGroupsHTML', true);
		$.post('/appinclude/action/groups/make_public.php', {GroupId:ThisGroupId}, function(Data){
			EndGrayOutArea();
			InsertMarkupFromAJAX(Data);
		});
	}
	
	this.MakePrivate = function(ThisGroupId){
		GrayOutArea('#FrameworkGroupsHTML', true);
		$.post('/appinclude/action/groups/make_private.php', {GroupId:ThisGroupId}, function(Data){
			EndGrayOutArea();
			InsertMarkupFromAJAX(Data);
		});
	}
	
	this.ShowPublicRenameDialog = function(GroupId){
		this.PublicRenameId = GroupId
		
		$('#PublicRenameGroupDuplicateNameWarning').hide();
		$('#PublicRenameGroupEmptyNameWarning').hide();
		
		DialogId = Dialog("<div id='PublicRenameGroupDialog'></div>", 500, "GroupObject.ClosePublicRenameDialog()");
		$('#PublicRenameGroupDiv').appendTo("#PublicRenameGroupDialog");
		RepositionDialog(DialogId, 500);
		$('#PublicRenameGroupGroupName').val($('#ManageGroup_'+GroupId).html());
		$('#PublicRenameGroupGroupName').focus();
	}
	
	this.ClosePublicRenameDialog = function(){
		$('#PublicRenameGroupDiv').appendTo("#EditGroupWrapper");
		CloseDialog('#PublicRenameGroupDialog');
	}
	
	this.SavePublicRename = function(){
		ThisGroupName = $('#PublicRenameGroupGroupName').val();
		
		if(ThisGroupName == ''){
			$('#PublicRenameGroupEmptyNameWarning').fadeIn('fast');
			return;
		}
		else{
			$('#PublicRenameGroupEmptyNameWarning').hide();
		}
		
		GrayOutArea('#PublicRenameGroupDiv', true);
		$.post('/appinclude/action/groups/make_public.php', {GroupId:this.PublicRenameId, NewName:ThisGroupName}, function(Data){
			EndGrayOutArea();
			InsertMarkupFromAJAX(Data);
		});
	}
	
	this.AddContactToGroup = function(DialogTitle){
		if(DialogTitle == null){
			DialogTitle = "Add to a group";
		}
		
		$('.QuickAddGroupName').show();
		
		Dialog("<div class='DialogHeader'>"+DialogTitle+"</div>"+
			"<div id='AddContactToGroup' style='font-size:12px; padding:20px;'>"+$('#AddGroupDialogSource').html()+"</div>", 450);
		
		AddTextAreaDefault('#AddToGroupNewGroupName', "Enter group name");
		
		$('#AddContactToGroup #AddToGroupNewGroupName').bind('keydown', 'return', function(){
			$('#AddContactToGroup #CreateGroupButton').click();
		});
	}
}

</SCRIPT>

<DIV id="FrameworkGroupsHTML"></DIV>
<DIV style="display: none;" id="CreateGroupWrapper">
<DIV id="CreateGroupDiv" align="center">
<DIV class="DialogHeader">		Create a new Group	</DIV>
<TABLE style="color: rgb(102, 102, 102); font-size: 14px; font-weight: bold;" 
cellSpacing="0" cellPadding="0">
  <TBODY>
  <TR>
    <TD align="left">
      <DIV style="display: none;" id="CreateGroupDuplicateNameWarning" class="Warning">
      		This name is not available. Please try a different name.	</DIV>
      <DIV style="display: none;" id="CreateGroupEmptyNameWarning" class="Warning">
      		Please enter a name for this group	</DIV>
      <DIV style="margin-top: 15px;">		Group Name	</DIV>
      <DIV><INPUT style="width: 370px;" id="NewGroupGroupName" class="BoldFormField" 
      name="GroupName" type="text"></DIV><BR>
      <DIV><A class="GreenButton" onclick="GroupObject.SaveGroup();" href="javascript://">Create 
      Group</A></DIV><BR></TD></TR></TBODY></TABLE></DIV></DIV>
<DIV style="display: none;" id="AddGroupDialogSource">You haven't created any 
groups yet. Enter a new one below.
<DIV style="margin-bottom: 10px; border-bottom-color: rgb(170, 170, 170); border-bottom-width: 1px; border-bottom-style: solid;">&nbsp;</DIV>
<DIV style="padding: 5px; color: white; font-size: 14px; font-weight: bold; display: none; background-color: rgb(231, 102, 25);" 
class="GroupNameWarning" align="center">			Please enter a name		</DIV>
<DIV style="padding: 5px; color: white; font-size: 14px; font-weight: bold; display: none; background-color: rgb(231, 102, 25);" 
class="GroupNameTaken" align="center">			This name isn't available.		</DIV>
<DIV class="QuickAddGroupName">		New Group: <INPUT id="AddToGroupNewGroupName" 
name="AddToGroupNewGroupName" maxLength="250" type="text"><SPAN style="display: none;" 
id="ValSpan_AddToGroupNewGroupName"></SPAN><INPUT id="CreateGroupButton" onclick="AddGroupObject.CreateGroupAndAddContact();" value="Create" type="button"></DIV></DIV></DIV>
<DIV id="AJAXPAGE_merge__individual_merge" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Merge Contacts - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = '';
	
	PageSettings["merge__individual_merge"] = TempPageSettings;
	
	</SCRIPT>

<SCRIPT type="text/javascript">

var MergeObject = new MergeClass();	


function MergeClass(){	
	this.CurrentSearchCall = 0;
	this.ContactId;
	this.Contact2;
	
	this.Init = function(){
		if($('#MergeSearch').val() != '')
			this.StartMergeSearch();
		
		this.Contact2 = 0;
		
		AddTextAreaDefault("#MergeSearch", "Search for a name, email, phone, etc.");
		
		$('#MergeSearch').bind('keydown', function(){
			MergeObject.StartMergeSearch();
		});
	}
	
	this.StartMergeSearch = function(){
		$('#MergeSearchResults').html("<div align='center'><br /><br />Searching...<br /><img src='style/default/images/main/loading.gif' /></div>");	
		
		this.CurrentSearchCall++;
		setTimeout("MergeObject.ExecuteMergeSearch("+this.CurrentSearchCall+")", 1000);
	}
	
	this.ExecuteMergeSearch = function(SearchCall){
		if(SearchCall == this.CurrentSearchCall){
			$.post('/appinclude/action/merge/contact_search.php', {ContactId:this.ContactId, SearchTerms:$('#MergeSearch').val()}, function(data){
				if(SearchCall == MergeObject.CurrentSearchCall){
					InsertMarkupFromAJAX(data);
					
					$('[id^=MergeSearchOptionResults]').bind('click', function(){
						$('.SuggestSelect').hide();
						$('.MergeButtonDiv').show();
						MergeObject.Contact2 = $(this).val();
					})
				}
			});
		}
	}
	
	this.RunMerge = function(){
		SecondContact = $("input[@name='MergeSearchOptionResults']:checked").val();
		jQuery.history.load("/app/Merge/Individual_Merge_Confirm?Contact1="+this.ContactId+"&Contact2="+this.Contact2);
	}
}

</SCRIPT>

<DIV id="FrameworkMergeHTML"></DIV></DIV>
<DIV id="AJAXPAGE_merge__individual_merge_confirm" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Merge Contacts - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = '';
	
	PageSettings["merge__individual_merge_confirm"] = TempPageSettings;
	
	</SCRIPT>

<SCRIPT type="text/javascript">

var MergeConfirmObject = new MergeConfirmClass();	

function MergeConfirmClass(){	
	
	this.SubmitConfirmForm = function(){
		GrayOutArea('#MergeConfirmForm', true);
		$.post("/appinclude/action/merge/resolve.php", $('#MergeConfirmForm').serialize(), function(Data){
			InsertMarkupFromAJAX(Data);
		});
	}
	
}

</SCRIPT>

<DIV id="FrameworkMergeConfirmHTML"></DIV></DIV>
<DIV id="AJAXPAGE_merge__bulk_merge_confirm" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Duplicate Contacts - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = '';
	
	PageSettings["merge__bulk_merge_confirm"] = TempPageSettings;
	
	</SCRIPT>

<SCRIPT type="text/javascript">

var BulkMergeObject = new BulkMergeClass();	

function BulkMergeClass(){	
	this.RunMerge = function(){
		GrayOutArea('#BulkMergeForm', true);
		DialogAlert("<div class='BoldDarkGray'>Your contacts are being merged. If you have many duplicates,\
					this could take a while. Please be patient.</div>");
		$.post('/appinclude/action/merge/bulk_resolve.php', $('#BulkMergeForm').serialize(), function(Data){
			InsertMarkupFromAJAX(Data);
		});
	}
	
}

</SCRIPT>

<DIV id="FrameworkBulkMergeConfirmHTML"></DIV></DIV>
<DIV id="AJAXPAGE_merge__bulk_merge" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Duplicate Contacts - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = true;
	TempPageSettings['JSBeforeAJAX'] = 'PermSidebarObject.HidePermSidebar(); BulkMergeIndexObject.Reset();';
	
	PageSettings["merge__bulk_merge"] = TempPageSettings;
	
	</SCRIPT>

<SCRIPT type="text/javascript">

var BulkMergeIndexObject = new BulkMergeIndexClass();

function BulkMergeIndexClass(){
	this.Reset = function(){
		ResizeEvent = "BulkMergeIndexObject.Resize()";
	}
	
	this.Resize = function(){
		$('.BulkMergeColumn').css('max-width', (Math.round($('#BodyMain').width()/6))+"px");
	}
}

</SCRIPT>

<DIV id="FrameworkBulkMergeHTML"></DIV></DIV>
<DIV id="AJAXPAGE_merge__bulk_merge_results" class="AJAXPageTemplate">
<SCRIPT type="text/javascript">
	
	TempPageSettings = new Array();
	TempPageSettings['PageTitle'] = 'Bulk Merge Complete - Less Annoying CRM';
	TempPageSettings['GetAJAXContent'] = false;
	TempPageSettings['JSBeforeAJAX'] = 'CloseDialogs();';
	
	PageSettings["merge__bulk_merge_results"] = TempPageSettings;
	
	</SCRIPT>

<SCRIPT type="text/javascript"></SCRIPT>

<DIV id="FrameworkBulkMergeResultsHTML">
<DIV class="PageHeader">
<H1>Excellent! The merge is complete</H1></DIV>
<DIV style="padding: 20px;">		Your duplicates have all been merged, so you 
should be good to go!		<BR><BR><A class="GreenButton" href="https://www.lessannoyingcrm.com/app/Workspace">Go 
to your Workspace</A></DIV></DIV></DIV>
<DIV id="AJAXPAGE_loadingpagegeneric" class="AJAXPageTemplate"></DIV>
<DIV style="display: none;" id="AJAXPAGE_NOTFOUND" class="AJAXPageTemplate">
<H1 style="font-size: 32px;">Oops! We can't find the page you're looking 
for.</H1>
<DIV style="color: rgb(153, 153, 153); font-size: 14px; font-weight: bold;">    
		If you think this is an error, please email us at     		<A href="mailto:info@lessannoyingcrm.com">info@lessannoyingcrm.com</A> 
   		and let us know.    		    		<BR><BR><A href="https://www.lessannoyingcrm.com/app">Go 
to your Workspace</A></DIV></DIV></DIV></DIV></DIV></DIV>
<DIV style="color: rgb(153, 153, 153); font-weight: bold; margin-top: 15px;" 
align="center"><A style="color: rgb(153, 153, 153);" href="https://www.lessannoyingcrm.com/">Home</A>&nbsp;&nbsp;|&nbsp;&nbsp;
			<A style="color: rgb(153, 153, 153);" href="https://www.lessannoyingcrm.com/app/Workspace">Log 
in</A>&nbsp;&nbsp;|&nbsp;&nbsp;			<A style="color: rgb(153, 153, 153);" href="https://www.lessannoyingcrm.com/help">Help 
and training</A>&nbsp;&nbsp;|&nbsp;&nbsp;			<A style="color: rgb(153, 153, 153);" 
href="https://www.lessannoyingcrm.com/about.php">About our 
company</A>&nbsp;&nbsp;|&nbsp;&nbsp;			<A style="color: rgb(153, 153, 153);" 
href="https://www.lessannoyingcrm.com/affiliates">Affiliate 
program</A>&nbsp;&nbsp;|&nbsp;&nbsp;			<A style="color: rgb(153, 153, 153);" 
href="http://www.lessannoyingsoftware.com/blog">Blog</A>&nbsp;&nbsp;|&nbsp;&nbsp;
			<A style="color: rgb(153, 153, 153);" href="https://www.lessannoyingcrm.com/contact.php">Contact 
us</A></DIV>
<DIV style="color: rgb(153, 153, 153); font-size: 11px; margin-top: 15px;" 
align="center">© 2013 - Less Annoying CRM, All rights reserved. (<A style="color: rgb(153, 153, 153);" 
href="https://www.lessannoyingcrm.com/privacy.php" rel="nofollow">Privacy 
Policy</A> - <A style="color: rgb(153, 153, 153);" href="https://www.lessannoyingcrm.com/terms.php" 
rel="nofollow">Terms of Service</A>)</DIV><BR>
<SCRIPT>
var HitUpdateTimeLimit = 15000;
$(function(){
	setTimeout("UpdateHit("+21829106+", 1)", HitUpdateTimeLimit);
});

function UpdateHit(ThisHitId, Iteration){
	if(Iteration > 60)
		return;
	/*
	$.post("/ajax/refreshsession.php", {HitId:21829106}, function(data){
		setTimeout("UpdateHit("+ThisHitId+", "+(Iteration+1)+")", HitUpdateTimeLimit);
	});*/
}
</SCRIPT>

<SCRIPT type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-10339499-3']);
  _gaq.push(['_trackPageview']);
  _gaq.push(['_trackPageLoadTime']);
	
  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</SCRIPT>

<SCRIPT id="IntercomSettingsScriptTag">
var intercomSettings = {
	email: "rookieport@gmail.com",
	created_at: 1371434553,
	'Has_Paid': 0,
	user_id: 39944,
	app_id: "a0fdljos"
};
/*
company: {
	    id: '39944',
	    name: '39944',
	    created_at: 1371434553,
	    monthly_spend: 10,
		has_paid: 0,
		num_users: 1,
	  },
	 */
</SCRIPT>

<SCRIPT>(function(){var w=window;var d=document;var i=function(){i.c(arguments)};i.q=[];i.c=function(args){i.q.push(args)};w.Intercom=i;function l(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://static.intercomcdn.com/intercom.v1.js';var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);}if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}})();</SCRIPT>

<SCRIPT type="text/javascript">if(!NREUMQ.f){NREUMQ.f=function(){NREUMQ.push(["load",new Date().getTime()]);var e=document.createElement("script");e.type="text/javascript";e.src=(("http:"===document.location.protocol)?"http:":"https:")+"//"+"d1ros97qkrwjf5.cloudfront.net/42/eum/rum.js";document.body.appendChild(e);if(NREUMQ.a)NREUMQ.a();};NREUMQ.a=window.onload;window.onload=NREUMQ.f;};NREUMQ.push(["nrfj","beacon-3.newrelic.com","f0360a668f","2141503","Z1BXYhNYC0ECUxALCl4aYEQIFgRCEx8UEApTUEZFT0kNQg==",0,674,new Date().getTime(),"","a4d49388c3ad5c9f","","",""]);</SCRIPT>
</BODY></HTML>
